FastAPI determines automatically: if the parameter appears in the path {} it is a path param, otherwise it is a query param.
Path parameters
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
# With validation
@app.get("/items/{item_id}")
def get_item(item_id: int = Path(ge=1, le=1000)):
return {"item_id": item_id}
Type annotations automatically:
- Convert the URL string to the required type
- Validate the value
- Document it in Swagger
Query parameters
from fastapi import Query
@app.get("/tasks/")
def list_tasks(
status: str | None = None, # optional
priority: int = 1, # with default
q: str | None = Query(None, min_length=3), # with validation
limit: int = Query(20, ge=1, le=100),
):
return {"status": status, "priority": priority, "q": q}
GET /tasks/?status=todo&priority=3&limit=10
Multiple values
from typing import List
@app.get("/tasks/")
def list_tasks(tags: List[str] = Query([])):
return {"tags": tags}
# GET /tasks/?tags=python&tags=django
Enum parameters
from enum import Enum
class TaskStatus(str, Enum):
todo = "todo"
in_progress = "in_progress"
done = "done"
@app.get("/tasks/")
def list_tasks(status: TaskStatus | None = None):
return {"status": status}
Mixed parameters
@app.get("/projects/{project_id}/tasks/")
def list_project_tasks(
project_id: int, # path
status: str | None = None, # query
limit: int = 20, # query
):
return {
"project_id": project_id,
"status": status,
"limit": limit,
}
FastAPI determines automatically: if the parameter appears in the path {} it is a path param, otherwise it is a query param.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!