Performance: Required query parameters
This affects the server response time and client experience by enforcing parameter presence before processing the request.
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items") def read_items(q: str = Query(...)): # Required parameter return {"q": q}
from fastapi import FastAPI app = FastAPI() @app.get("/items") def read_items(q: str = None): if q is None: return {"error": "Missing query parameter q"} return {"q": q}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual parameter check inside endpoint | N/A | N/A | N/A | [X] Bad |
| FastAPI required query parameter (Query(...)) | N/A | N/A | N/A | [OK] Good |
Query(...) tells FastAPI this parameter is required and must be in the URL.item_id of type int in FastAPI?Query(...) as the default value.Query(...) correctly, making item_id required. def read_item(item_id: int = Query(None)): uses Query(None) which makes it optional. def read_item(item_id: int = None): uses default None without Query, optional. def read_item(item_id: int = Body(...)): uses Body(...) which makes it a required body field, not query parameter.from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(...)):
return {"query": q}/items/ without the q query parameter?Query(...) makes the parameter required. If missing, FastAPI returns an error automatically.name:from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/users/")
async def get_user(name: str = Query(None)):
return {"user": name}Query(None) which means the parameter is optional.Query(...) instead of Query(None).category (string) and limit (integer). Both must be required. Which code snippet correctly enforces this?Query(...) to be required.Query(...) for both. async def get_items(category: str = None, limit: int = None) uses None defaults, making them optional. async def get_items(category: str, limit: int = Query(None)) makes only limit optional. async def get_items(category: str = Query(None), limit: int = Query(...)) makes category optional.Pass the test and this pattern moves unknown