Performance: Multiple response types
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 |
return HTMLResponse(content='Hello') is used?from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
@app.get('/greet', responses={200: {'content': {'application/json': {}, 'text/html': {}}}})
async def greet(html: bool = False):
if html:
return HTMLResponse(content='Hello')
return JSONResponse(content={'message': 'Hello'})from fastapi import FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse
app = FastAPI()
@app.get('/data', responses={200: {'content': {'application/json': {}, 'text/plain': {}}}})
async def data(response_type: str):
if response_type == 'json':
return JSONResponse(content={'key': 'value'})
else:
return 'Just plain text'?format=html is given. Which approach correctly implements this with multiple response types?from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, HTMLResponse
app = FastAPI()
@app.get('/info', responses={200: {'content': {'application/json': {}, 'text/html': {}}}})
async def info(request: Request):
format = request.query_params.get('format')
if format == 'html':
# What to return here?
else:
return JSONResponse(content={'info': 'data'})Pass the test and this pattern moves unknown