A response model tells FastAPI to validate, filter and document what the endpoint returns.
Why Use Response Models?
Filter Out Sensitive Data: If your internal database object contains fields like
hashed_password,
internal_notes, orsecret_token, a response model automatically strips those fields out before sending the response.Validate Outgoing Data: FastAPI checks that your own code returns the exact data types promised.
Generate Accurate API Docs: FastAPI uses the response model to build complete example payloads and schemas in the interactive Swagger UI.
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr
app = FastAPI()
# 1. Input Model (includes password)
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
# 2. Output / Response Model (excludes password)
class UserPublic(BaseModel):
id: int
username: str
email: EmailStr
# 3. Route using response_model
@app.post("/users/", response_model=UserPublic)
def create_user(user: UserCreate):
# Simulate saving to a database with extra internal fields
saved_user_in_db = {
"id": 101,
"username": user.username,
"email": user.email,
"hashed_password": "secret_hashed_value",
"is_superuser": False
}
# FastAPI automatically filters out hashed_password and is_superuser
return saved_user_in_db