Difficulty: Beginner
What is response_model in FastAPI, how does it relate to the function's return type, and why does it matter for security?
response_model tells FastAPI the shape of the data an endpoint returns. FastAPI validates the returned value against that model, filters out any fields the model does not declare, serializes it to JSON and documents it in OpenAPI. Since FastAPI 0.89 you can get the same behaviour by annotating the function's return type, e.g. -> UserOut.
When your handler returns, FastAPI:
password_hash on your ORM object never reaches the client if UserOut does not list it./docs.This is why response models are a security feature, not just documentation. A classic leak is returning the same model you used for input or the raw DB row, exposing hashes, internal flags or other users' data.
| Approach | When to use |
|---|---|
def f() -> UserOut | Default choice. Type checkers and FastAPI agree. |
@app.get(..., response_model=UserOut) | When you return something of a different type, e.g. an ORM User object, and want FastAPI to convert it. |
| Both present | response_model wins for FastAPI; the annotation is only for your editor. |
response_model=None | Disable response model generation, e.g. when returning a Response subclass directly. |
To build a Pydantic model from an ORM object, set model_config = ConfigDict(from_attributes=True) on the response model.
response_model_exclude_unset=True: omit fields that were never set, useful for PATCH-like partial data.response_model_exclude_none=True: drop fields whose value is None.response_model_include / response_model_exclude: quick filters, though a dedicated model is cleaner and shows correctly in docs.list[UserOut] or a generic Page[UserOut] for collections.JSONResponse directly. FastAPI skips response model validation and filtering for Response objects, so you lose the safety net.class UserOut(UserCreate) inherits password. Prefer a shared UserBase that both extend.A user service typically has UserBase (shared fields), UserCreate(UserBase) adding password, and UserOut(UserBase) adding id and created_at. The DB model has hashed_password, which no response model mentions, so it can never leak even if a developer returns the ORM object by mistake.
from datetime import datetime, timezone
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, EmailStr
app = FastAPI()
class UserBase(BaseModel):
name: str
email: EmailStr
class UserCreate(UserBase):
password: str
class UserOut(UserBase):
model_config = ConfigDict(from_attributes=True) # allow ORM objects
id: int
created_at: datetime
class UserInDB: # stand-in for an ORM model
def __init__(self, **kw):
self.__dict__.update(kw)
@app.post("/users", response_model=UserOut, status_code=201)
def create_user(user: UserCreate):
db_user = UserInDB(id=1, name=user.name, email=user.email,
hashed_password="$argon2id$...",
created_at=datetime.now(timezone.utc))
return db_user # hashed_password is filtered out by UserOut
Because the return type differs from UserOut, response_model is set on the decorator. from_attributes lets Pydantic read attributes from the ORM-style object.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Profile(BaseModel):
name: str
bio: str | None = None
city: str | None = None
@app.get("/profiles/{pid}", response_model_exclude_unset=True)
def get_profile(pid: int) -> Profile: # annotation acts as response_model
return Profile(name="Asha", city="Chennai")
The return annotation doubles as the response model. bio was never set, so exclude_unset omits it from the JSON.
response_model, return type annotation, output filtering, response_model_exclude_unset, data leakage