Performance: Why structured responses matter
Structured responses impact how quickly clients can parse and render data, affecting interaction speed and perceived responsiveness.
from fastapi import FastAPI from pydantic import BaseModel from typing import List class Item(BaseModel): id: int name: str class ResponseModel(BaseModel): data: List[Item] message: str app = FastAPI() @app.get("/items", response_model=ResponseModel) async def get_items(): return {"data": [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"}], "message": "Success"}
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def get_items(): return {"data": [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"}], "message": "Success"}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unstructured JSON response | N/A | N/A | Higher due to delayed rendering | [X] Bad |
| Structured Pydantic response model | N/A | N/A | Lower due to predictable parsing | [OK] Good |
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
@app.get('/user', response_model=User)
async def get_user():
return {'id': 1, 'name': 'Alice', 'extra': 'ignored'}
What will the API response contain?from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get('/item', response_model=Item)
async def read_item():
return {'name': 'Book'}Pass the test and this pattern moves unknown