Performance: Multiple response types
MEDIUM IMPACT
This affects server response time and client rendering speed by controlling how data is serialized and sent over the network.
from fastapi import FastAPI from fastapi.responses import JSONResponse from fastapi.templating import Jinja2Templates from fastapi import Request app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get("/item") async def get_item(request: Request, response_type: str = "json"): data = {"item": "value"} if response_type == "html": return templates.TemplateResponse("item.html", {"request": request, "data": data}) return JSONResponse(content=data)
from fastapi import FastAPI from fastapi.responses import JSONResponse, HTMLResponse app = FastAPI() @app.get("/item") async def get_item(response_type: str): data = {"item": "value"} if response_type == "html": return HTMLResponse(content=f"<html><body>{data['item']}</body></html>") else: return JSONResponse(content=data)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual HTML string + JSON switch | Minimal | Minimal | Higher due to larger payload | [X] Bad |
| Template rendering + JSONResponse | Minimal | Minimal | Lower due to optimized payload | [OK] Good |