Performance: Optional query parameters
This affects the server response time and the amount of data processed before sending the response, impacting initial load and interaction speed.
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items") async def read_items(q: Optional[str] = None): if q: return {"q": q} return {"message": "No query provided"}
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items") async def read_items(q: str): # q is expected but optional is not declared return {"q": q}
| Pattern | Server Processing | Error Handling | Response Time | Verdict |
|---|---|---|---|---|
| Required query parameter without default | High (validates every request) | High (errors on missing param) | Slower due to error handling | [X] Bad |
| Optional query parameter with default None | Low (skips validation if missing) | None (no errors on missing param) | Faster response for missing param | [OK] Good |
q of type str in FastAPI?from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(q: Optional[str] = None):
if q:
return {"query": q}
return {"query": "No query"}/items/ without any query parameters?q optional:from fastapi import FastAPI
app = FastAPI()
@app.get("/search/")
def search(q: str = None):
return {"q": q}page with a default of 1, but if the user sends page=0, it should return an error. How would you declare page to achieve this behavior?Pass the test and this pattern moves unknown