Performance: Custom response classes
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 |
Custom response classes in FastAPI?PlainTextResponse to send plain text content.content argument.from fastapi import FastAPI
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/", response_class=HTMLResponse)
async def read_root():
return "Welcome
"
response_class=HTMLResponse, which sets the content type to HTML.Content-Type: text/html.from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/data")
async def get_data():
return JSONResponse(content=[1, 2, 3], status_code="200")
Content-Disposition to prompt file download with the filename.Pass the test and this pattern moves unknown