Lesson 8 of 59How backends work
Path and Query Parameters
Read typed values from the URL with path and query parameters, and validate them with Annotated, Query and Path.
Almost every request carries input in its URL: which todo, which page, which filter. If you read those values by hand you end up writing the same int(...) calls and range checks in every route, and forgetting one is how ?limit=1000000 takes down a database. FastAPI turns the URL into typed, validated function arguments, as long as you declare what you expect.
Anatomy of a URL
Take GET /users/7/todos?done=true&limit=5. The path is /users/7/todos; some of its segments are path parameters that identify a resource. After the ? comes the query string: name=value pairs joined by &, used for optional things like filters, sorting and pagination.
The raw URL. Everything arrives as text, even the numbers.
Path parameters
Write the parameter in braces in the path, and give the function an argument with the same name and a type hint.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/todos/{todo_id}")
def get_user_todo(user_id: int, todo_id: int):
return {"user_id": user_id, "todo_id": todo_id}GET /users/7/todos/3 returns {"user_id": 7, "todo_id": 3} with real integers. GET /users/seven/todos/3 never reaches your function. FastAPI answers 422 with a body that says exactly what went wrong:
{
"detail": [
{
"type": "int_parsing",
"loc": ["path", "user_id"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "seven"
}
]
}loc tells the client where the bad value was (the path, field user_id). Your function body only ever sees clean, typed data.
Order matters. Routes are checked top to bottom, and {user_id} matches any segment, including the word me.
@app.get("/users/me") # must come first
def read_me(): ...
@app.get("/users/{user_id}")
def read_user(user_id: int): ...If you swap them, GET /users/me matches /users/{user_id} first and fails with a 422, because "me" is not an integer.
/users/{user_id} is declared before /users/me. What does GET /users/me return?Query parameters
Any function argument that is not in the path and has a simple type (int, str, bool, float, an enum, a list of those) is read from the query string.
@app.get("/todos")
def list_todos(done: bool | None = None, skip: int = 0, limit: int = 20, q: str | None = None):
results = todos
if done is not None:
results = [t for t in results if t["done"] == done]
if q:
results = [t for t in results if q.lower() in t["title"].lower()]
return results[skip : skip + limit]The rules come straight from Python:
- Has a default: optional.
limitis20when the URL does not mention it. - Default is
Nonewith a type likebool | None: optional, andNonemeans "not given". That is how you tell "no filter" apart fromdone=false. - No default: required. Leave it out and you get a
422with"type": "missing".
For bool, FastAPI accepts true, 1, yes, on (and their opposites) in any case.
For the route @app.get("/todos/{todo_id}"), where does each argument come from?
How the binding works
Here is the trick FastAPI uses, built with the standard library. It reads the function's signature, finds each argument's type hint, and converts the matching query value.
Press Run (⌘ Enter) to see what happens.Notice the third call collects every error before answering, so the client can fix them all at once. FastAPI does the same.
Using bind and search from above, what does this print?
status, body = bind(search, "q=tea&done=OFF") print(status, body["done"], body["limit"])
Validation with Annotated, Query and Path
Types catch "not a number". For "a number between 1 and 100" you add constraints. The modern style puts them in Annotated, which attaches extra information to a type hint without changing the type.
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/todos")
def list_todos(
limit: Annotated[int, Query(ge=1, le=100)] = 20,
q: Annotated[str | None, Query(min_length=2, max_length=50)] = None,
tag: Annotated[list[str], Query()] = [],
):
...
@app.get("/todos/{todo_id}")
def get_todo(todo_id: Annotated[int, Path(gt=0, description="The todo's id")]):
...ge,gt,le,lt: greater or equal, greater than, less or equal, less than (numbers).min_length,max_length,pattern: for strings (patternis a regular expression).list[str]withQuery()reads repeated keys:?tag=home&tag=urgentgives["home", "urgent"].description,alias,deprecated: show up in/docs.alias="item-query"lets the URL use a name that is not a valid Python identifier.
Now ?limit=500 is rejected with "type": "less_than_equal" before your code runs. That one line protects your database from someone asking for a million rows.
limit: Annotated[int, Query(ge=1, le=100)] = 20, what happens on GET /todos?limit=0?Why Annotated instead of `limit: int = Query(20, le=100)`?
Older FastAPI code puts Query(...) in the default slot. It still works, but Annotated is the recommended style because the function stays a normal Python function: the default really is 20, so you can call list_todos() directly in a test or a script. You can also reuse a constrained type: Limit = Annotated[int, Query(ge=1, le=100)], then limit: Limit = 20 everywhere.
Enums for fixed choices
When a parameter has a fixed set of values, use an Enum. FastAPI validates against it and /docs shows a dropdown.
from enum import StrEnum
class SortOrder(StrEnum):
newest = "newest"
oldest = "oldest"
title = "title"
@app.get("/todos")
def list_todos(sort: SortOrder = SortOrder.newest):
if sort is SortOrder.title:
...
return {"sort": sort}?sort=random gets a 422 listing the allowed values. StrEnum (Python 3.11+) members are also real strings, so they serialize to JSON as "newest".
sort: SortOrder instead of sort: str and an if check inside the function?List params: ?tag=a&tag=b
A filter often takes several values: todos tagged home or urgent, orders in status paid or shipped. The HTTP convention that FastAPI follows is to repeat the key: ?tag=home&tag=urgent. Declare the parameter as a list and wrap it in Query():
@app.get("/todos")
def list_todos(
tag: Annotated[list[str], Query(max_length=10)] = [],
status: Annotated[list[TodoStatus] | None, Query()] = None,
):
...Three details matter here. First, the Query() is required for lists. Without it, FastAPI sees tag: list[str] and decides it is a JSON body, because a list is not a "simple type". Your GET route silently expects a body and /docs shows a request body editor. Second, max_length on a list limits the number of items, so ?tag= repeated 10,000 times becomes a 422 with too_long instead of a 10,000-way IN (...) clause. Third, list items are validated one by one, so list[TodoStatus] with an enum rejects ?status=lost precisely.
The default can be [] in an Annotated signature. Python's "mutable default" warning does not bite here, because FastAPI builds a fresh list for each request.
Some APIs prefer comma lists, ?tag=home,urgent. FastAPI does not split those for you: you would get the single string "home,urgent". If you must support them (for example to match an existing public API), take a str and split it in a dependency, or with a field_validator(mode="before") on a query model. For a new API, repeated keys are the better default because every HTTP client library produces them from a list.
You can see the raw shapes with the standard library:
Press Run (⌘ Enter) to see what happens.Note the fourth line. The standard library drops empty values unless you ask it not to, but Starlette keeps them. In FastAPI, ?done= gives the parameter the empty string, so done: bool | None = None answers with a 422 bool_parsing error rather than treating it as absent. Frontends that build URLs from empty form fields hit this all the time; the fix belongs in the client (leave the key out), or in a mode="before" validator that maps "" to None if you must accept it.
What does the standard library return here?
from urllib.parse import parse_qs
print(parse_qs("status=open&status=closed&limit="))Query parameter models
Once a list endpoint has eight filters, the signature is long, and the same filters get copied into the export endpoint and the count endpoint. Since FastAPI 0.115 you can group query parameters into a Pydantic model and declare it with Query():
from typing import Annotated, Literal
from fastapi import Query
from pydantic import BaseModel, ConfigDict, Field
class TodoFilters(BaseModel):
model_config = ConfigDict(extra="forbid")
limit: Annotated[int, Field(ge=1, le=100)] = 20
status: list[TodoStatus] = []
q: Annotated[str | None, Field(min_length=2, max_length=50)] = None
order_by: Literal["created_at", "due_date", "title"] = "created_at"
@app.get("/todos")
def list_todos(filters: Annotated[TodoFilters, Query()]):
return repo.search(filters)Each field becomes its own query parameter, so the URL is still ?status=open&limit=5 and /docs still lists each parameter separately. List fields work without any extra Query(). Your function receives one typed object that you can hand straight to a repository or a service.
extra="forbid" is worth more here than on bodies. A client that writes ?stauts=open normally gets the unfiltered list, with no error, and may act on the wrong data. With forbid, it gets a 422 with "type": "extra_forbidden" and "loc": ["query", "stauts"]. Recent releases (0.159 and later) also accept an optional model, Annotated[TodoFilters | None, Query()] = None, which gives you None when the URL carries none of its fields.
Cursor pagination, sort allow-lists and filter grammars for big tables are covered in List Endpoints That Scale, which builds on this model.
Header and cookie parameters
Header() and Cookie() work just like Query(), they only read from a different part of the request:
from fastapi import Cookie, Header
@app.get("/reports")
def reports(
x_request_id: Annotated[str | None, Header()] = None,
accept_language: Annotated[str, Header()] = "en",
theme: Annotated[str | None, Cookie()] = None,
):
...Header names are case-insensitive, and they use hyphens, which are not valid in Python names. FastAPI therefore converts underscores: x_request_id reads the X-Request-ID header. In the rare case where a header really contains underscores, pass Header(convert_underscores=False), but know that many proxies, including nginx by default, drop such headers. A list[str] header collects repeated headers.
Headers and cookies can be grouped into models too, Annotated[CommonHeaders, Header()] and Annotated[Prefs, Cookie()]. One warning, learned the hard way: do not put extra="forbid" on a header model. Every real request carries host, user-agent, accept and friends, and each one becomes an extra_forbidden error, so every request fails with a 422. Forbid extras on query models, never on header models.
In practice, most header reading belongs in a dependency rather than in routes: the bearer token for auth, the tenant id, the idempotency key. Cookies for login sessions have their own security rules (HttpOnly, SameSite, CSRF), which Cookie Sessions, CSRF and Logout That Works covers in depth.
Common mistakes
You already met the first one, route order: /users/{user_id} declared before /users/me swallows me. Declare fixed paths first, or give the variable segment a type that me cannot satisfy and accept the 422, which is worse. Two related surprises:
- A path parameter matches one segment. For a file path like
/files/docs/2026/report.pdf, declare{file_path:path}, which matches the rest of the path including slashes. Put such routes last, because they match almost anything. - An
intpath parameter accepts any size of integer, but Postgresintegerstops at about 2.1 billion.GET /todos/99999999999then fails in the database with a 500. AddPath(gt=0, le=2_147_483_647), or use string ids.
The second classic is trailing slashes. FastAPI treats /items and /items/ as different paths. If you declare @app.get("/items/") and a client calls /items, FastAPI does not 404; it answers 307 Temporary Redirect to /items/.
The frontend calls the path without the slash. The load balancer ends TLS.
The fixes, from most to least preferred: pick one convention (no trailing slash is the most common) and declare every route that way; make sure the server trusts the proxy's X-Forwarded-Proto (fastapi run enables proxy headers, but only trusts them from the addresses in --forwarded-allow-ips); and if you want strict behaviour, FastAPI(redirect_slashes=False) turns the redirect into a plain 404. A redirect in a test is easy to spot: TestClient follows it silently, so assert client.get("/items", follow_redirects=False).status_code.
@app.get("/items/"). What does GET /items return by default?Practice
Bind and validate query parameters
Do what FastAPI does with limit: Annotated[int, Query(ge=1, le=100)] = 20. Write bind_query(query, schema).
query is a raw query string without the ? (for example "limit=5&done=true"). schema describes the parameters, in order:
{
"limit": {"type": "int", "default": 20, "ge": 1, "le": 100},
"done": {"type": "bool", "default": None},
"q": {"type": "str"}, # no "default" key: required
}Return {"values": {...}} when everything is valid, or {"errors": [...]} listing every error in schema order:
- missing required:
"q: missing" - conversion failed:
"limit: not a valid int"/"done: not a valid bool" - out of range:
"limit: must be >= 1"/"limit: must be <= 100"
Details: types are "int", "bool" and "str". Booleans accept true/1/yes/on and false/0/no/off in any case. A missing optional parameter takes its default (defaults are not validated). Ignore query names that are not in the schema.
- path parameter
- A variable segment of the path, like
{todo_id}in/todos/{todo_id}. Required, identifies a resource. - query parameter
- A
name=valuepair after?. Optional when it has a default; used to filter, sort and paginate. - Annotated
Annotated[int, Query(le=100)]adds metadata (like constraints) to a type hint without changing the type.- 422
- Unprocessable Content: FastAPI's response when input fails validation.
detaillists each error'slocandtype. - StrEnum
- An enum whose members are strings. As a parameter type it restricts input to a fixed set of values.
- query parameter model
- A Pydantic model declared with
Annotated[Model, Query()]. Each field becomes a query parameter, andextra="forbid"rejects typos. - Header()
- Reads a parameter from a request header. Underscores in the name become hyphens, so
x_request_idreadsX-Request-ID. - redirect_slashes
- FastAPI's default behaviour of answering a missing or extra trailing slash with a 307 redirect. Set it to False to get a 404 instead.