Query Parameters: Filters and Options
A FastAPI function parameter that isn't in the route's path is read from the query string, so a default of None makes an optional filter, a bool reads yes-or-no values such as true and 0, and several filters combine in one request.
Apprentice · FastAPI · REST API · Updated
After this lesson you can
- Add optional query parameters with a default of None, and filter a list only by the ones a request sent
- Read whole numbers and yes-or-no values from the query string, and combine two filters in one request
Key takeaways
- A function parameter that isn't in the route's path becomes a query parameter, read from the ?name=value part of the address.
- A query parameter with no default is required, and FastAPI answers 422 when it's missing. A default of None, written int | None = None, makes it optional.
- A bool query parameter accepts true and false, 1 and 0, yes and no, or on and off, and FastAPI answers 422 for any other word.
- Several filters go in one request, joined with &, and each one is checked only when it was sent.
- A misspelled name in the query string is ignored, not refused, so the list comes back unfiltered.
Most lists an app shows are narrowed down by the person looking: shoes in size 9, only the orders still open, flights under $300. The app asks for the narrower list by adding filters to the address, and the API has to read them, use the ones that were sent and ignore the ones that weren't. This lesson shows how FastAPI reads those filters.
The example is the Rolling Dice café again: guests at the door ask "Do you have something for four of us?", and the staff app should answer from the shelf.
A filter in the address
The answer could come from a path like /games/players/4. Then "for four of us, under half an hour" needs /games/players/4/minutes/30, and every mix of filters needs its own route, in a fixed order.
Addresses have a place for this instead: the query string, the part after a ? (read "question mark"), such as /games?players=4. It holds name and value pairs, joined with & (read "and"). In FastAPI, any function parameter that isn't in the route's path is read from the query string. It's called a query parameter:
@app.get("/games")
def list_games(players: int):
found = []
for game in GAMES:
if game["min_players"] <= players <= game["max_players"]:
found.append(game)
return found
The if keeps a game when players is between its smallest and largest group. /games?players=4 answers with Harbor Lights (2 to 4 players) and Moon Mice (3 to 6). As with a path parameter, the type hint turns the text "4" into a number, and /games?players=four gets a 422.
But /games on its own, the plain list the app showed before, now answers 422 too:
{"detail":[{"type":"missing","loc":["query","players"],"msg":"Field required","input":null}]}
A parameter with no default value is required, and this request didn't send it.
Optional filters: a default of None
A filter should be used when it's sent and skipped when it isn't. Give the parameter a default of None, Python's value for "nothing here":
@app.get("/games")
def list_games(players: int | None = None):
if players is None:
return GAMES
found = []
for game in GAMES:
if game["min_players"] <= players <= game["max_players"]:
found.append(game)
return found
int | None = None is read "int or None, defaulting to None": the value is a whole number when the request sends one, and None when it doesn't. Now /games answers with all three games, and /games?players=4 with two.
A default doesn't have to be None. max_minutes: int = 30 would mean "30 minutes unless the request says otherwise". None is the usual choice for a filter, because it means "not sent", which no real number can mean.
Two filters, and yes-or-no values
Guests also ask for something quick, and staff want only the games that are on the shelf right now, not out at a table. Each filter is one more parameter, and the loop skips a game as soon as one sent filter rules it out:
@app.get("/games")
def list_games(players: int | None = None, max_minutes: int | None = None, available: bool | None = None):
found = []
for game in GAMES:
if players is not None and not game["min_players"] <= players <= game["max_players"]:
continue
if max_minutes is not None and game["minutes"] > max_minutes:
continue
if available is not None and game["available"] != available:
continue
found.append(game)
return found
continue skips to the next game, so a game reaches found.append only when it passes every filter that was sent. /games?players=4&max_minutes=30 answers with one game, the only one that passes both:
[{"id":2,"title":"Moon Mice","min_players":3,"max_players":6,"minutes":20,"available":false}]
A bool query parameter accepts the words people and programs use for yes and no: true and false, 1 and 0, yes and no, on and off, in capitals or not. /games?available=yes and /games?available=1 both answer with Harbor Lights and Tile Town. /games?available=maybe gets a 422 whose message says Input should be a valid boolean.
Names must match exactly
A query parameter's name in the address has to match the function's parameter exactly, capital letters included. A typo isn't an error: /games?player=4 (no s) answers 200 with all three games, because no parameter is named player and the filter was never sent. When a filtered list comes back suspiciously full, check the spelling first.
The docs page at /docs lists every query parameter under the route, with its type and an empty box for each, so you can try any mix of filters with Try it out:
Check yourself
2 questions to try on the lesson page.
So what
Query parameters let one route answer every combination of filters an app needs, and a default of None keeps each filter out of the way until somebody asks for it.