Performance: Why query parameters filter data
This affects server response time and network payload size by controlling how much data is sent to the client.
from fastapi import FastAPI, Query app = FastAPI() items = [{"id": i, "value": f"Item {i}"} for i in range(1000)] @app.get("/items") def read_items(min_id: int = Query(0)): filtered = [item for item in items if item["id"] >= min_id] return filtered
from fastapi import FastAPI app = FastAPI() items = [{"id": i, "value": f"Item {i}"} for i in range(1000)] @app.get("/items") def read_items(): return items
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No filtering (all data sent) | Minimal DOM nodes (depends on client) | 0 reflows from server data | High paint cost due to large data | [X] Bad |
| Server-side filtering with query params | Minimal DOM nodes (only filtered data) | 0 reflows from server data | Lower paint cost due to smaller data | [OK] Good |
category in FastAPI?category: str = None, which means the parameter is optional and of type string.from fastapi import FastAPI
app = FastAPI()
items = [
{"name": "apple", "category": "fruit"},
{"name": "carrot", "category": "vegetable"}
]
@app.get("/items")
async def read_items(category: str = None):
if category:
return [item for item in items if item["category"] == category]
return items/items?category=fruit?category is given, then filters items matching that category.color:from fastapi import FastAPI
app = FastAPI()
items = [
{"name": "shirt", "color": "blue"},
{"name": "pants", "color": "black"}
]
@app.get("/items")
def read_items(color):
return [item for item in items if item["color"] == color]category and max_price. Which code snippet correctly implements this filtering?category and max_price are optional, so they need default values (None) to allow filtering only when provided.Pass the test and this pattern moves unknown