Performance: Boolean query parameters
This affects how quickly the server parses and validates query parameters, impacting response time and user experience.
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def read_items(active: bool = False): return {"active": active}
from fastapi import FastAPI, Query app = FastAPI() @app.get("/items") async def read_items(active: str = Query("false")): is_active = active.lower() == "true" return {"active": is_active}
| Pattern | CPU Parsing Cost | Validation Overhead | Error Risk | Verdict |
|---|---|---|---|---|
| Manual string parsing | High (string operations per request) | Manual, error-prone | Higher (case sensitivity, typos) | [X] Bad |
| Native boolean parameter | Low (automatic parsing) | Automatic, robust | Low (built-in validation) | [OK] Good |
/items?active=true?
from fastapi import FastAPI, Query
from typing import Optional
app = FastAPI()
@app.get('/items')
async def read_items(active: Optional[bool] = Query(None)):
return {"active": active}from fastapi import FastAPI, Query
app = FastAPI()
@app.get('/items')
async def read_items(active: bool = Query()):
return {"active": active}available. If available is true, return only available items; if false, only unavailable items; if missing, return all items. Which code correctly implements this behavior?Pass the test and this pattern moves unknown