Performance: Default values
This affects the server response time and request parsing speed by how default values are handled in endpoint parameters.
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def read_items(q: str = "default"): return {"q": q}
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def read_items(q: str = None): if q is None: q = "default" return {"q": q}
| Pattern | CPU Overhead | Code Complexity | Response Time Impact | Verdict |
|---|---|---|---|---|
| Manual default assignment inside endpoint | Slightly higher due to condition check | More complex with extra if statements | Negligible but unnecessary | [X] Bad |
| Using FastAPI default parameter values | Minimal CPU overhead | Simpler and cleaner code | Negligible and optimal | [OK] Good |
limit in a FastAPI endpoint?limit: int = 10. Using Query() is optional for extra validation.from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 5):
return {"skip": skip, "limit": limit}/items/ without any query parameters?skip and limit have default values: 0 and 5 respectively.from fastapi import FastAPI
app = FastAPI()
@app.get("/users/")
def get_users(limit: int = Query(10)):
return {"limit": limit}Query(10) but does not import Query from fastapi.category with a default value of "all". However, if the client sends an empty string "", you want to treat it as None (no category filter). Which approach correctly implements this behavior?Pass the test and this pattern moves unknown