Performance: Custom response classes
MEDIUM IMPACT
This affects how quickly the server sends responses and how the browser processes them, impacting page load speed and responsiveness.
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/good") async def good_response(): data = {"message": "Hello"} return JSONResponse(content=data)
from fastapi import FastAPI, Response app = FastAPI() @app.get("/bad") async def bad_response(): data = {"message": "Hello"} content = str(data) # converting dict to string manually return Response(content=content, media_type="application/json")
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual string conversion in Response | N/A (server-side) | N/A | Higher due to delayed content | [X] Bad |
| Using JSONResponse for JSON data | N/A | N/A | Lower due to faster content delivery | [OK] Good |
| Reading full file into memory | N/A | N/A | Higher due to delayed response start | [X] Bad |
| Using FileResponse for streaming files | N/A | N/A | Lower due to streaming and faster start | [OK] Good |