0
0
FastAPIframework~8 mins

Multiple response types in FastAPI - Performance & Optimization

Choose your learning style9 modes available
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.
Returning different response formats based on client needs
FastAPI
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)
Using template rendering for HTML and JSONResponse for JSON ensures efficient serialization and smaller, optimized payloads.
📈 Performance GainReduces CPU overhead and payload size, improving LCP by ~50ms and lowering server load
Returning different response formats based on client needs
FastAPI
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)
Manually constructing HTML strings and switching response types in the endpoint can cause inconsistent serialization and larger payloads.
📉 Performance CostAdds extra CPU for string concatenation and larger HTML payload increases LCP by ~50ms on slow networks
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Manual HTML string + JSON switchMinimalMinimalHigher due to larger payload[X] Bad
Template rendering + JSONResponseMinimalMinimalLower due to optimized payload[OK] Good
Rendering Pipeline
The server serializes data into the chosen response type, sends it over the network, and the browser parses and renders it accordingly.
Server Serialization
Network Transfer
Browser Parsing
Rendering
⚠️ BottleneckServer Serialization and Network Transfer
Core Web Vital Affected
LCP
This affects server response time and client rendering speed by controlling how data is serialized and sent over the network.
Optimization Tips
1Use FastAPI's built-in JSONResponse and template rendering for different response types.
2Avoid manual string concatenation for HTML to reduce CPU and payload size.
3Choose response types that minimize payload size to improve LCP.
Performance Quiz - 3 Questions
Test your performance knowledge
Which response type choice most improves Largest Contentful Paint (LCP) in FastAPI?
AManually building HTML strings for all responses
BUsing JSONResponse for JSON and template rendering for HTML
CReturning plain text for all responses
DSending large HTML payloads regardless of client needs
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the endpoint, and inspect the response size and content type.
What to look for: Look for smaller payload size and correct content-type headers indicating efficient response format.