In FastAPI, how do Query() and Path() inside Annotated add constraints such as ge, le and max_length, and what makes a query parameter required?
answer
- metadata inside Annotated
- the default after the equals sign
- nullable is not optional
- lists need an explicit marker
basics
~20 sWrite the constraint in a marker inside Annotated, such as Annotated[int, Query(ge=1, le=100)] = 20; FastAPI validates it and answers 422 on violation. A query parameter is required exactly when it has no default, even if its type allows None.
solid answer
~30 sYou put a `Query()` or `Path()` marker inside `Annotated` and pass constraints to it: `limit: Annotated[int, Query(ge=1, le=100)] = 20`, `q: Annotated[str | None, Query(min_length=3, max_length=50)] = None`, `item_id: Annotated[int, Path(ge=1)]`. FastAPI validates them after conversion, answers 422 with types such as `less_than_equal`, and documents them in the schema. The default goes after `=`; `Query(default=...)` inside `Annotated` fails at startup. Requiredness comes only from the default: no default means required, so `page: int | None` must still be sent, while `= None` makes it optional. Path parameters are always required, and a `list[str]` query parameter needs an explicit `Query()`.
code
python · 17 linesfrom typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/shops/{shop_id}/items")
async def search_items(
shop_id: Annotated[int, Path(ge=1)],
q: Annotated[str | None, Query(min_length=3, max_length=50)] = None,
tags: Annotated[list[str], Query()] = [],
min_price: Annotated[float | None, Query(ge=0)] = None,
limit: Annotated[int, Query(ge=1, le=100)] = 20,
):
return {"shop_id": shop_id, "q": q, "tags": tags,
"min_price": min_price, "limit": limit}go deeper
Recall the shape Annotated[type, Query(...)] = default, and that a parameter with no default is required.
Explain why int | None without a default is still required, why the default may not go inside the marker, and why lists need Query() to come from the query string.
Show you bound every paging and size parameter, read 422 types like less_than_equal to diagnose clients, and migrate old default-style markers to Annotated deliberately.
Set a team rule that public parameters carry explicit bounds and Annotated markers, since unbounded limits and implicit requiredness are where API contracts quietly drift.
## Declaring constraints with a marker FastAPI's parameter markers, `Query()`, `Path()`, `Header()` and `Cookie()`, carry two kinds of information besides the source: - **Validation**: `gt`, `ge`, `lt`, `le` for numbers; `min_length`, `max_length` and `pattern` for strings. - **Metadata** for the generated schema: `title`, `description`, `alias`, `deprecated`, `include_in_schema`, `examples`. The recommended form, supported since FastAPI 0.95 and used throughout the current docs, places the marker inside `Annotated`: ```python limit: Annotated[int, Query(ge=1, le=100)] = 20 q: Annotated[str | None, Query(min_length=3, max_length=50)] = None item_id: Annotated[int, Path(ge=1)] ``` FastAPI converts the raw string to the annotated type first, then applies the constraints. A violation never reaches your function; the client gets a **422** whose entries name the rule, for example `{"type": "less_than_equal", "loc": ["query", "limit"], "ctx": {"le": 100}}` for `?limit=500`. Values are rejected, not clamped. The `regex` keyword still exists but emits a deprecation warning; `pattern` replaced it. ## Where the default lives With `Annotated`, the **default is the function default after `=`**. Passing `default=` to the marker as well is ambiguous, and FastAPI refuses it when the route is registered: "`Query` default value cannot be set in `Annotated` for 'q'. Set the default value with `=` instead." The older style puts the marker in the default position, `q: str | None = Query(default=None, max_length=50)`. It still works and you will meet it in existing code, but the function no longer has a real Python default, so calling it outside FastAPI passes a marker object instead of `None`. ## What makes a query parameter required | Declaration | Required? | Request without `page` | |---|---|---| | `page: int` | yes | 422, `type` `missing` | | `page: int \| None` | **yes**, may be null | 422, `type` `missing` | | `page: int \| None = None` | no | `page` is `None` | | `page: int = 1` | no | `page` is `1` | The rule is short: **a default makes it optional, nothing else does**. Allowing `None` in the type only says that a missing default may legitimately be `None`; it does not create one. An empty value is not a missing value either: `?page=` sends the empty string, and `int` conversion fails with `int_parsing`. **Path parameters are always required**, because the path cannot match without them. Without `Annotated` a default on a path parameter is ignored; with `Annotated` FastAPI rejects it at startup with "Path parameters cannot have default values". ## Lists of query values A `list` annotation without a marker is treated as a **request body**. To accept `?tags=a&tags=b`, declare the marker explicitly: ```python tags: Annotated[list[str], Query()] = [] ``` - Each repeated key adds one element; FastAPI does **not** split `?tags=a,b`, which arrives as the single element `"a,b"`. - `list[int]` converts and validates every element; a bare `list` checks nothing inside. - A list default such as `["new"]` is used when the key is absent. ## Numbers, floats and metadata - `gt` and `lt` are strict bounds, `ge` and `le` inclusive. For a `float`, `Query(gt=0)` accepts `0.5` and rejects `0`, which `ge=1` could not express. - The same keywords work on `Path()`, `Header()` and `Cookie()`, because all the markers share one base class, `Param`. - `title` and `description` only change the generated docs; they validate nothing. - `deprecated=True` keeps the parameter working and marks it as deprecated in the docs, which is how you retire a parameter while clients still send it. - `include_in_schema=False` hides a parameter from the docs while still binding and validating it. ## Practical guidance - Put bounds on every paging and size parameter (`ge=1`, `le=100`) so a client cannot ask for an unbounded page. - Use `alias` when the public name is not a Python identifier, such as `item-query`. - Keep custom checks that need only the value itself in the type; anything needing a database belongs in a dependency.
- In FastAPI, how do you declare a query parameter that clients must send but that may be empty or null?Declare it with a type that allows `None` and no default, such as `q: Annotated[str | None, Query()]`. FastAPI marks it required, so leaving it out gets a 422 of type `missing`. Sending `?q=` passes the empty string, which a `str` accepts. Requiredness comes from the missing default, nullability from the type.
- In FastAPI, why do existing codebases still show `q: str = Query(default=None)`, and should you keep it?Before FastAPI 0.95 the marker had to be the default value, so older code uses that form and it still works. New code should use `Annotated` with the default after `=`, because the function keeps a real Python default and stays callable outside FastAPI. Mixing both forms on one parameter is rejected.
- Typing a query parameter as int | None makes it optional by itself.
- Query(le=100) clamps a larger value down to 100.
- Inside Annotated you should set the default with Query(default=...).
- FastAPI splits ?tags=a,b into two list elements.
- A list[str] parameter is read from the query string without any marker.
- A default value on a path parameter makes it optional.