FastAPI
Query Parameters
Parse query strings with defaults and validation.
By EZ4Code Team
queryparamsvalidation
Code
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/search")
def search(q: str = Query(..., min_length=2, max_length=50)):
return {"q": q}
@app.get("/items")
def list_items(skip: int = 0, limit: int = Query(10, ge=1, le=100)):
return {"skip": skip, "limit": limit}
@app.get("/tags")
def by_tags(tags: list[str] = Query(default=[])):
return {"tags": tags}Explanation
Query() lets you validate query parameters with constraints like min_length, ge, and le. Required params use ... as the default; optional ones omit it or supply a value. Annotated as list[str], a repeated query key becomes a list automatically.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Dependency Injection
Share logic via Depends and yield-based dependencies.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.
Async and Await
Define async handlers and run blocking work in a thread.