Response models and response filtering

Difficulty: Beginner

Question

What is response_model in FastAPI, how does it relate to the function's return type, and why does it matter for security?

Answer

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.

What FastAPI does with the response model

When your handler returns, FastAPI:

  1. Takes the returned object (a dict, ORM object or another Pydantic model).
  2. Validates it against the response model; if it does not fit, that is a server bug, so FastAPI raises an error and the client gets a 500, not bad data.
  3. Keeps only the declared fields. A password_hash on your ORM object never reaches the client if UserOut does not list it.
  4. Serializes the result to JSON and adds the schema to /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.

response_model vs return annotation

ApproachWhen to use
def f() -> UserOutDefault 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 presentresponse_model wins for FastAPI; the annotation is only for your editor.
response_model=NoneDisable 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.

Fine-tuning the output

  • 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.

Common mistakes

  • Returning a JSONResponse directly. FastAPI skips response model validation and filtering for Response objects, so you lose the safety net.
  • Using inheritance carelessly: class UserOut(UserCreate) inherits password. Prefer a shared UserBase that both extend.
  • Assuming filtering is free. Validation of big lists costs CPU; for very large exports, consider streaming or returning a pre-serialized response.

In real APIs

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.

Response model as an output filter. Only fields declared in the response model survive to the JSON response.
  1. Handler returns ORM user: Includes id, email and hashed_password.
  2. Validate against UserOut: Mismatch here is a server error.
  3. Drop undeclared fields: hashed_password is removed.
  4. Serialize to JSON: Client sees only id, name and email.

Code examples

Separate input and output models

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.

Return annotation and exclude_unset

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.

Key points

  • response_model validates, filters, serializes and documents the output
  • A return type annotation works as response_model since FastAPI 0.89; the decorator argument takes priority
  • Returning a Response object directly bypasses response model filtering
  • Use from_attributes=True to build response models from ORM objects
  • Never let output models inherit from input models that contain passwords

Common follow-up questions

  • What happens if the returned data does not match the response model?
  • How would you return different response schemas for different status codes in the docs?
  • How do you structure Base, Create, Update and Out models for one entity?
  • What is the performance cost of response model validation on large lists?

Interview tips

  • Lead with the security angle: response models stop accidental data leaks
  • Mention that a mismatch is a 500 because it is the server's fault, which shows you know the semantics
  • Show you know the modern return-annotation style and when the decorator is still needed

Concepts covered

response_model, return type annotation, output filtering, response_model_exclude_unset, data leakage

More FastAPI Interview questions