In FastAPI, how does a separate output model keep a sign-up endpoint from returning the user's password hash?
answer
- three models for one user
- only declared fields leave
- response_model or the return annotation
- UserIn, UserOut, UserInDB
basics
~20 sDeclare 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 sI 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 linesfrom 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
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.
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.
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.
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.