← Back to FastAPI, page 1

fastapi-0005 · Easy fresher

What does response_model (or a return type annotation) do in FastAPI, and why does it matter for security?

A response model declares the shape of the response. FastAPI validates the returned data against it, serialises it, filters out fields that are not in the model and documents it in OpenAPI. That filtering prevents leaking fields like password hashes when you return a database object. You can declare it with a return type annotation or response_model=..., and tune output with response_model_exclude_unset.

Full answer

Two ways to declare the output:

python
@app.get("/users/{id}")
def get_user(id: int) -> UserOut: ...

@app.get("/users/{id}", response_model=UserOut)
def get_user(id: int): ...

If both are present, response_model wins. Use response_model when the function returns something else (for example a dict or an ORM object) that should be converted into UserOut.

What FastAPI does with it:

  1. Validates the return value against the model. Returning wrong data is a server bug, so it raises an error (500), not a 422.
  2. Filters: only fields in the model are included. If your internal object has password_hash, and UserOut does not, the hash never reaches the client.
  3. Serialises with Pydantic (dates, UUIDs, decimals become JSON).
  4. Documents the schema in OpenAPI.

A common pattern is separate models per direction:

  • UserCreate (input): name, email, password.
  • UserOut (output): id, name, email.
  • An internal or database model with the hash.

Options:

  • response_model_exclude_unset=True: leave out fields that were never set (good for PATCH-style responses).
  • response_model_exclude_none=True: drop None values.
  • response_model=list[UserOut] for lists.
  • Returning a Response object directly skips the response model entirely.

For ORM objects, give the output model model_config = ConfigDict(from_attributes=True) (v1 called this orm_mode) so Pydantic reads attributes.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict

app = FastAPI()


class UserInDB:                       # stands in for an ORM object
    def __init__(self, id, name, email, password_hash, phone=None):
        self.id, self.name, self.email = id, name, email
        self.password_hash, self.phone = password_hash, phone


class UserOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    name: str
    email: str
    phone: str | None = None


DB = {1: UserInDB(1, "Sana", "sana@example.edu", "$argon2id$v=19$...")}


@app.get("/users/{user_id}", response_model=UserOut)
def get_user(user_id: int):
    return DB[user_id]                # has password_hash, but it is filtered out


@app.get("/users/{user_id}/compact", response_model=UserOut, response_model_exclude_none=True)
def get_user_compact(user_id: int):
    return DB[user_id]


c = TestClient(app)
print(c.get("/users/1").json())
print(c.get("/users/1/compact").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'id': 1, 'name': 'Sana', 'email': 'sana@example.edu', 'phone': None} {'id': 1, 'name': 'Sana', 'email': 'sana@example.edu'}

Key points

  • Response model validates, filters, serialises and documents output
  • Filtering stops sensitive fields from leaking
  • response_model= overrides the return annotation
  • Use separate input and output models
  • from_attributes=True reads ORM objects

Common mistakes

  • Returning ORM objects without a response model and leaking internal fields
  • Reusing the input model (with password) as the output model
  • Forgetting from_attributes=True when returning ORM objects
  • Expecting response validation errors to be 422; they are server errors

Follow-ups

  • How would you return different fields to admins and normal users?
  • What happens if your endpoint returns data that fails the response model?
  • What is the cost of response validation on very large lists?

Tips

  • Lead with the security benefit
  • Show separate input and output models
  • Mention from_attributes for ORM objects