0
0
FastAPIframework~8 mins

Custom response classes in FastAPI - Performance & Optimization

Choose your learning style9 modes available
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.
Sending JSON responses with custom formatting
FastAPI
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)
Uses FastAPI's optimized JSONResponse which serializes data efficiently and sets correct headers.
📈 Performance GainFaster serialization and smaller response size, improving LCP
Sending JSON responses with custom formatting
FastAPI
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")
Manually converting dict to string can cause incorrect JSON formatting and extra processing on the server.
📉 Performance CostBlocks response serialization longer, delaying first byte sent
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual string conversion in ResponseN/A (server-side)N/AHigher due to delayed content[X] Bad
Using JSONResponse for JSON dataN/AN/ALower due to faster content delivery[OK] Good
Reading full file into memoryN/AN/AHigher due to delayed response start[X] Bad
Using FileResponse for streaming filesN/AN/ALower due to streaming and faster start[OK] Good
Rendering Pipeline
Custom response classes affect the server's serialization and delivery of content, which impacts the browser's ability to start rendering the page quickly.
Server Serialization
Network Transfer
Browser Parsing
⚠️ BottleneckServer Serialization when inefficient custom responses are used
Core Web Vital Affected
LCP
This affects how quickly the server sends responses and how the browser processes them, impacting page load speed and responsiveness.
Optimization Tips
1Use FastAPI's built-in response classes like JSONResponse and FileResponse for better performance.
2Avoid manual serialization or reading large files fully into memory before responding.
3Streaming responses reduce server blocking and improve user-perceived load speed.
Performance Quiz - 3 Questions
Test your performance knowledge
Which FastAPI response class is best for sending JSON data efficiently?
AFileResponse
BResponse with manual string conversion
CJSONResponse
DPlain Response with bytes
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and inspect the response timing and size for your API calls.
What to look for: Look for Time to First Byte (TTFB) and Content Download time; faster times indicate better response performance.