Performance: Query parameter validation
This affects the server response time and the speed at which the client receives valid data, impacting perceived page load and interaction speed.
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items") def read_items(q: str = Query(..., min_length=3)): return {"q": q}
from fastapi import FastAPI app = FastAPI() @app.get("/items") def read_items(q: str = None): if q is None or len(q) < 3: return {"error": "Query too short"} # process q return {"q": q}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation in endpoint code | 0 (server-side only) | 0 | 0 | [!] OK but slower response |
| FastAPI Query parameter validation | 0 (server-side only) | 0 | 0 | [OK] Fast, efficient validation |
Query() in FastAPI for query parameters?Query()Query() is used in FastAPI to add validation rules to query parameters, such as minimum length or value ranges.Query() does not doq with a minimum length of 3 in FastAPI?q: str = Query(min_length=3).age is set to 15?from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(age: int = Query(..., ge=18)):
return {"age": age}age requires a value greater or equal to 18 (ge=18).from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/search/")
async def search_items(q: str = Query(min_length=5)):
return {"query": q}Query(min_length=5) implicitly sets default=Ellipsis, making q required with string length validation.... is not needed; the code correctly validates required query parameters. No error.tags which must be a list of strings, each at least 2 characters long. Which is the correct way to validate this?Query() supports min_items for lists but min_length applies to strings, not list elements.Query().Pass the test and this pattern moves unknown