Difficulty: Beginner
What is response_model in FastAPI and why is it important?
The `response_model` parameter on a path operation decorator specifies the Pydantic model used to validate and filter the response data. It serves three purposes:
1. Filtering: Strips fields not in the response model (e.g., passwords) 2. Validation: Ensures the response matches the expected schema 3. Documentation: Adds the response schema to OpenAPI docs
This separates input models (request body) from output models (response), which is critical for security - you can return a database object and have FastAPI automatically exclude sensitive fields.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
name: str
email: str
password: str
class UserResponse(BaseModel):
name: str
email: str
# no password field
@app.post("/users", response_model=UserResponse)
def create_user(user: UserCreate):
# password is in `user` but won't be returned
return user # FastAPI filters it using UserResponse
# Use response_model_exclude_unset=True to omit unset optional fields
@app.get("/users/{id}", response_model=UserResponse, response_model_exclude_unset=True)
def get_user(id: int):
return {"name": "Alice", "email": "alice@example.com"}
response_model, output filtering, security, serialization