skip to content

Response Model Filtering

response_model or a return annotation filters and validates the output; Pydantic serializes it in Rust since 0.130 unless a response class is set. Interviewers ask how an output model hides a hash.

on this pageshow

explore

questions

6

In FastAPI, how does a separate output model keep a sign-up endpoint from returning the user's password hash?

level: juniorimportance: must knowfreq 70%

answer

  1. three models for one user
  2. only declared fields leave
  3. response_model or the return annotation
  4. UserIn, UserOut, UserInDB

basics

~20 s

Declare an output model without password fields, such as UserOut, as the endpoint's response_model or return type. FastAPI validates the returned data against it and sends only its declared fields, so hashed_password never reaches the JSON.

solid answer

~30 s

I split the user into three Pydantic models: `UserIn` with the plaintext `password` for the request body, `UserInDB` with `hashed_password` for storage, and `UserOut` with neither for responses. The path operation declares `response_model=UserOut`, or `-> UserOut` when the function really returns that type. FastAPI validates the returned value against `UserOut` and serializes only `UserOut`'s fields, so returning the full `UserInDB` still sends just the public ones. Reusing `UserIn` as the response model would echo the password back, and a shared base class keeps the common fields in one place.

code

python · 42 lines
python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel


class UserIn(BaseModel):
    username: str
    email: str
    password: str


class UserOut(BaseModel):
    username: str
    email: str


class UserInDB(BaseModel):
    username: str
    email: str
    hashed_password: str


def fake_hash(password: str) -> str:
    return "not-a-real-hash:" + password  # stand-in for a real password hasher


app = FastAPI()


@app.post("/users", response_model=UserOut, status_code=201)
async def sign_up(user_in: UserIn) -> UserInDB:
    return UserInDB(
        username=user_in.username,
        email=user_in.email,
        hashed_password=fake_hash(user_in.password),
    )


client = TestClient(app)
r = client.post("/users", json={"username": "ada", "email": "[email protected]", "password": "s3cret"})
print(r.status_code, r.json())
# 201 {'username': 'ada', 'email': '[email protected]'}

go deeper

for a junior

Recall the three models, UserIn, UserInDB and UserOut, and that the response model on the decorator or the return annotation decides which fields leave the endpoint.

for a middle

Explain the mechanism: FastAPI validates the returned value against the response model with from_attributes, serializes only declared fields, and puts that model in the OpenAPI response schema.

for a senior

Name what bypasses the filter: a returned Response object, response_model=None, extra="allow" on the output model, and dict or Any fields that carry nested data unfiltered.

for a principal

Treat the output model as the reviewable contract: one declaration per path operation that both enforces and documents what leaves, instead of trusting every handler body.

## The problem: one model for input and output A sign-up endpoint receives a **plaintext password** and stores a **password hash**. Neither belongs in the response. The tempting shortcut is to use the request model as the response model too: ```python @app.post("/users", response_model=UserIn) async def sign_up(user_in: UserIn) -> UserIn: return user_in ``` That echoes the password straight back. On this endpoint it goes to the same client that sent it, but the moment the same model is reused on `GET /users/{id}` or an admin listing, every caller receives every user's secret. Hand-deleting keys from a dict in each handler does not scale either: the first new handler that forgets is a leak. ## Three models for three jobs FastAPI's documented answer is to give each stage of the user's life its own **Pydantic model**: | Model | Used for | Password field | |---|---|---| | `UserIn` | the request body of sign-up | `password` (plaintext) | | `UserInDB` | what the code stores and loads | `hashed_password` | | `UserOut` | what the API sends back | none | - `UserIn` is the body parameter, so FastAPI validates the incoming JSON against it. - `UserInDB` is internal; it never appears in a decorator. - `UserOut` is the **response model**, the contract for what may leave the endpoint. To avoid repeating `username`, `email` and `full_name` three times, put them on a `UserBase` and let the three models subclass it, each adding only its difference. ## How FastAPI applies the output model When a path operation has a response model, either `response_model=UserOut` on the decorator or a return annotation such as `-> UserOut`, FastAPI does the following with the data the function returns (a returned `Response` object is the exception, covered below): 1. **Validates** it against the response model. FastAPI calls Pydantic with `from_attributes=True`, so a dict, another model or an ORM object is read for the fields `UserOut` declares. 2. **Filters** it: only the declared fields are serialized. An extra `hashed_password` attribute or key is not part of `UserOut`, so it is not in the output. 3. **Documents** it: the response model becomes the 200 response schema in OpenAPI, so `/docs` shows clients the safe shape, not the stored one. If the returned data cannot satisfy the model, for example a required field is missing, FastAPI raises a server error instead of sending a wrong shape. A broken handler then produces a 500, not a partial leak. `response_model` lives on the decorator (`@app.post(...)`), not on the function. If both it and a return annotation exist, `response_model` wins, which lets the function be annotated `-> UserInDB` (true for the type checker) while FastAPI sends `UserOut`. ## What can still leak The output model is a filter only for data that goes through it. Review these cases: - **An output model with `extra="allow"`.** With `model_config = ConfigDict(extra="allow")`, keys the model does not declare are kept as extras and serialized. Pydantic's default, `extra="ignore"`, drops them. - **A field typed `dict` or `Any` on the output model.** It carries whatever nested data is put in it, unfiltered. - **Returning a `Response` object directly**, such as a `JSONResponse` built from the row. FastAPI passes a returned response through without applying the response model. - **`response_model=None`**, which turns the model off for that path operation. - **Reusing `UserIn` or `UserInDB` as the response model**, which declares the secret field and so sends it. ## Checking that it holds A filter you cannot see working is a filter you will eventually break. Two quick checks catch most regressions: - **A test on the response body.** Call the sign-up endpoint with `TestClient` and assert the exact set of keys in `response.json()`, not just the status code. A test that only checks `201` passes while the hash leaks. - **The schema in `/docs`.** The 201 response for the path should show `UserOut`, with no password field. If it shows the stored model, the response model is wrong or missing. - **A grep in review.** Search for `response_model=None`, `-> Any` without a `response_model`, and handlers that build a `JSONResponse` from a stored record. Each is a place where the filter does not apply. ## Why this belongs to the framework, not each handler Declaring the output model once on the path operation moves the guarantee out of handler bodies. A reviewer checks one line, the response model, instead of reading every return statement, and the generated schema shows the same contract the filter enforces.

  • What happens if the sign-up handler returns a JSONResponse built from the stored user instead of the model?
    FastAPI hands a returned `Response` straight to the client: no validation, no filtering, no response model. If that `JSONResponse` was built from the stored record's dict, `hashed_password` goes out. Return data and let the response model shape it; build a `Response` yourself only when you also choose its body from safe fields.
  • Can the output model itself let an undeclared field through?
    Yes. With `model_config = ConfigDict(extra="allow")`, validating a dict that carries `hashed_password` keeps it as an extra and the serializer emits it. Under Pydantic's default `extra="ignore"` undeclared keys are dropped. A field typed `dict` or `Any` on the output model also passes through whatever nested data it holds.

  • The request model can double as the response model; the password only goes back to its sender.
  • A return annotation is just for type checkers; FastAPI ignores it at runtime.
  • Returning the database object sends every attribute unless you convert it to a dict first.
  • An output model with extra="allow" still drops keys it does not declare.
  • Deleting the hash key in each handler is as safe as declaring an output model.
open as a page

In FastAPI, how do response_model and a return type annotation differ, and which one wins when a path operation declares both?

level: middleimportance: must knowfreq 60%

basics

~20 s

Both declare the response model FastAPI validates, filters and documents. The return annotation also satisfies type checkers; response_model is a decorator parameter for when the function returns something else. If both are set, response_model wins; response_model=None disables it.

open as a page

In FastAPI, how do you declare a paginated list-of-users endpoint so every returned row is validated and stripped to the public fields?

level: middleimportance: should knowfreq 45%

basics

~20 s

Declare the response model as list[UserOut] or a page model with items: list[UserOut]. FastAPI validates every item, reads ORM rows by attribute, and sends only UserOut's fields; one invalid row makes the whole response a 500.

open as a page

A FastAPI endpoint sets response_model_exclude_unset=True, yet returning the stored user model still sends every default field; why, and how do you fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

FastAPI rebuilds a returned object of another class into the response model by reading its attributes, so every field it finds counts as set and nothing is excluded. Return the response model itself or a subclass, or return stored.model_dump(exclude_unset=True).

open as a page

In FastAPI 0.143, when does Pydantic write a declared response model straight to JSON bytes, and why does any response_class, even an app-wide default, take a route off that path?

level: seniorimportance: should knowfreq 20%

basics

~20 s

Since 0.130, a return type or response_model with no response_class lets Pydantic's dump_json write the JSON bytes in one pass. Any explicit class, even JSONResponse or an app-wide default, makes Pydantic build Python data first for the class to render.

open as a page

As a lead, would you require every JSON endpoint in a FastAPI codebase to declare a response model, and how would you enforce it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Yes, for APIs others consume: the model filters output to listed fields, documents it for generated clients and, since 0.130, is the fast JSON path. The costs are model upkeep and a 500 when a return stops fitting; a schema test enforces it.

open as a page