Careeroza
Query Parameters
Example
Function arguments that are not in the path are read from the query string (?skip=0&limit=10). Defaults make them optional:
from fastapi import FastAPI
app = FastAPI()
COURSES = ["HTML", "CSS", "JavaScript", "SQL", "Python", "Docker"]
@app.get("/courses")
def list_courses(skip: int = 0, limit: int = 3, search: str | None = None):
items = [c for c in COURSES if not search or search.lower() in c.lower()]
return {"total": len(items), "items": items[skip: skip + limit]}Requests and responses
GET /courses
→ 200 {"total": 6, "items": ["HTML", "CSS", "JavaScript"]}
GET /courses?skip=3&limit=2
→ 200 {"total": 6, "items": ["SQL", "Python"]}
GET /courses?search=s
→ 200 {"total": 3, "items": ["CSS", "JavaScript", "SQL"]}Required and Boolean Query Parameters
Example
A parameter without a default is required. Booleans accept true/false, 1/0, yes/no, on/off:
from fastapi import FastAPI
app = FastAPI()
@app.get("/search")
def search(q: str, exact: bool = False):
return {"q": q, "exact": exact}Requests and responses
GET /search?q=fastapi&exact=yes
→ 200 {"q": "fastapi", "exact": true}
GET /search
→ 422 {"detail": [{"type": "missing", "loc": ["query", "q"], "msg": "Field required", "input": null}]}