Performance: Response model declaration
This affects the API response serialization speed and the size of data sent over the network, impacting time to first byte and overall response time.
from fastapi import FastAPI from pydantic import BaseModel class ItemResponse(BaseModel): id: int name: str app = FastAPI() @app.get("/items/{item_id}", response_model=ItemResponse) async def read_item(item_id: int): item = get_item_from_db(item_id) return item
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): item = get_item_from_db(item_id) # returns full DB model return item
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No response model, full DB object returned | N/A | N/A | Larger JSON payload delays browser rendering | [X] Bad |
| Response model declared with limited fields | N/A | N/A | Smaller JSON payload speeds up browser rendering | [OK] Good |
response_model in a FastAPI route?response_model tells FastAPI what data shape to send back, ensuring output matches a defined structure.response_model in the route decorator.response_model=Item. Others use incorrect parameter names./user/1?
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
password: str
@app.get('/user/{user_id}', response_model=User)
def get_user(user_id: int):
return {"id": user_id, "name": "Alice", "password": "secret", "token": "abc123"}response_model=User tells FastAPI to return only fields defined in User model, ignoring extra fields like token.id, name, password, and extra token. The extra token is removed in output.@app.get('/products', response_model=Product)
def get_products():
return [{"id": 1, "name": "Book"}, {"id": 2, "name": "Pen"}]
Assuming Product is a Pydantic model for a single product.response_model=Product expects a single product instance.id and name fields, hiding email and password. Given this User model:
class User(BaseModel):
id: int
name: str
email: str
password: str
Which is the best way to declare the response model in your route to achieve this?email and password, define a new Pydantic model with only id and name and use it as the response_model.Pass the test and this pattern moves unknown