0
0
FastapiHow-ToBeginner · 3 min read

How to Use response_model in FastAPI for Response Validation

In FastAPI, use response_model in your path operation decorator to specify the data model for the response. This ensures the output matches the model's structure and automatically converts and filters the response data.
📐

Syntax

The response_model parameter is used in FastAPI route decorators to declare the expected response data type. It takes a Pydantic model class that defines the shape of the response.

Example parts:

  • @app.get("/items/{item_id}", response_model=Item): Declares the response model.
  • Item: A Pydantic model class describing the response fields.
  • The function returns data that FastAPI validates and converts to match Item.
python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    return {"name": "Sample", "price": 10.5, "extra": "ignored"}
💻

Example

This example shows a FastAPI app with a response_model that filters extra fields and validates the response data type automatically.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
    # The returned dict has an extra field 'description' which will be ignored
    return {"name": "Book", "price": 12.99, "description": "A nice book"}
Output
{"name":"Book","price":12.99}
⚠️

Common Pitfalls

Common mistakes when using response_model include:

  • Returning data that does not match the model fields or types, causing validation errors.
  • Expecting response_model to modify the original data instead of just filtering the response.
  • Not using Pydantic models for response_model, which is required.

Example of a wrong and right way:

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    age: int

# Wrong: returning a list instead of a dict matching User
@app.get("/user_wrong", response_model=User)
async def user_wrong():
    return ["john", 30]  # This will cause validation error

# Right: returning a dict matching User
@app.get("/user_right", response_model=User)
async def user_right():
    return {"username": "john", "age": 30}
📊

Quick Reference

ParameterDescriptionExample
response_modelDefines the Pydantic model for response validation and serializationresponse_model=Item
response_model_exclude_unsetExclude fields not explicitly set in the response modelresponse_model_exclude_unset=True
response_model_includeInclude only specified fields in the responseresponse_model_include={"name"}
response_model_excludeExclude specified fields from the responseresponse_model_exclude={"price"}

Key Takeaways

Use response_model to declare the expected response data shape with Pydantic models.
FastAPI automatically validates and filters the response data to match the model.
Returning data that doesn't match the model causes validation errors.
Extra fields in the returned data are ignored unless explicitly included.
Always use Pydantic models for response_model to ensure proper serialization.