Careeroza
Parameter Validation
Query() and Path()
Example
Add rules with Annotated and Query/Path: lengths, number ranges, regex patterns, descriptions for the docs:
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(
item_id: Annotated[int, Path(ge=1, description="The item ID")],
q: Annotated[str | None, Query(min_length=3, max_length=20)] = None,
page: Annotated[int, Query(ge=1, le=100)] = 1,
):
return {"item_id": item_id, "q": q, "page": page}Requests and responses
GET /items/5?q=book&page=2
→ 200 {"item_id": 5, "q": "book", "page": 2}
GET /items/0
→ 422 {"detail": [{"type": "greater_than_equal", "loc": ["path", "item_id"], "msg": "Input should be greater than or equal to 1", "input": "0", "ctx": {"ge": 1}}]}
GET /items/5?q=ab
→ 422 {"detail": [{"type": "string_too_short", "loc": ["query", "q"], "msg": "String should have at least 3 characters", "input": "ab", "ctx": {"min_length": 3}}]}List Query Parameters
Example
Repeat a parameter to send a list: ?tag=a&tag=b.
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/filter")
def filter_by_tags(tag: Annotated[list[str], Query()] = []):
return {"tags": tag}Requests and responses
GET /filter?tag=python&tag=api
→ 200 {"tags": ["python", "api"]}