As a lead, would you require every JSON endpoint in a FastAPI codebase to declare a response model, and how would you enforce it?
answer
- an allow-list on the way out
- the schema clients generate from
- the 0.130 fast path comes with it
- a misfit becomes a 500
- check the generated schema in CI
basics
~20 sYes, 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.
solid answer
~40 sWithout a declared type an endpoint sends whatever it returns: a new `password_hash` on the stored object goes out the day it is added, and the OpenAPI schema shows an empty response, so generated clients get an untyped value. A declared model, `-> UserOut` or `response_model=UserOut`, is an allow-list: FastAPI validates the return value and sends only the model's fields, and since 0.130 Pydantic writes those bytes in one pass when no response class is set. The costs are an output model per resource to keep in step, and a return that no longer fits becomes a 500, so response models need tests. Endpoints that return a `Response` on purpose, files, redirects and streams, are exempt. A test walks `app.openapi()` and fails on any JSON success response with an empty schema.
code
python · 34 linesfrom fastapi import FastAPI
from pydantic import BaseModel
class UserOut(BaseModel):
id: int
name: str
app = FastAPI()
@app.get("/users/{user_id}")
def read_user(user_id: int) -> UserOut:
return {"id": user_id, "name": "ada", "password_hash": "x"} # hash filtered out
@app.get("/legacy")
def legacy():
return {"id": 1, "password_hash": "x"} # sent as is, documented as {}
def undeclared_json_operations(app: FastAPI) -> list[str]:
found = []
for path, operations in app.openapi()["paths"].items():
for method, operation in operations.items():
for status, response in operation["responses"].items():
schema = response.get("content", {}).get("application/json", {}).get("schema")
if status.startswith("2") and schema == {}:
found.append(f"{method.upper()} {path}")
return found
print(undeclared_json_operations(app)) # ['GET /legacy']go deeper
Know that a declared response model limits what an endpoint sends to the model's fields.
Explain what an endpoint without a model sends and what its OpenAPI entry looks like.
Weigh the upkeep and the new 500s against leaks, and say which endpoints are exempt.
Turn the convention into a rule with a CI check and a rollout plan that does not break production.
## What an endpoint without a model sends A FastAPI path operation with no return annotation and no `response_model` has no response field. Whatever it returns is run through `jsonable_encoder` and sent: every key of a dict, every attribute FastAPI can encode. Two things follow: - **Nothing is filtered.** If the stored user later gains a `password_hash` or a `totp_secret`, the endpoint sends it from that day on, and no test that only checks the fields it knows about will notice. - **Nothing is documented.** The operation's success response in the OpenAPI schema is an empty schema, so `/docs` shows nothing useful and generated clients get an untyped value. ## What a mandatory model buys Declaring `-> UserOut` or `response_model=UserOut` turns the response into an **allow-list**: - FastAPI validates the returned value against the model and sends only the model's fields; - the schema documents exactly that shape, which client generators and reviewers rely on; - since 0.130, with no `response_class` set, Pydantic writes those bytes in one pass, so the safe path is also the fast one and nobody is tempted to bypass it for speed. For an API with consumers outside the team, or data that must not leak, those three are worth a rule rather than a habit. ## What it costs - **Upkeep.** Each resource gains an output model that must follow the stored shape. Inheritance from a shared base keeps the duplication small, but every new public field is now a deliberate edit. - **New 500s.** A returned value that no longer fits the model, a declared field missing or of the wrong type, fails response validation and the client gets a 500 instead of a quietly wrong body. That is the point, but it means response models need tests, and a model stricter than the real data will surface in production unless staging traffic exercises it. - **Some friction** for endpoints whose shape is genuinely dynamic; they need a union, a generic container or an explicit exemption. ## Where the rule stops Endpoints that return a `Response` on purpose, file downloads, redirects, HTML pages and streams, have no JSON body to filter. They are exempt, but they should still say what they return through `response_class` or the `responses` parameter so the docs are not left empty. ## Enforcing it Review catches some cases; a test catches all of them. Walk `app.openapi()`, look at every operation's 2xx responses, and fail on any `application/json` response whose schema is empty, with an allowlist for the deliberate exceptions. Because the schema is generated from the routes, the check covers a new endpoint the moment it exists. A lint rule requiring a return annotation on path operation functions is a cheaper first line, but it misses `response_model=None` and annotations of `dict`. ## Rolling it out On an existing codebase, I would start with endpoints that return stored objects, since they leak first; add their models; run the full test suite and watch staging logs for response validation errors, fixing the model or the data each time; and only then switch on the CI check, so the rule arrives as a guard rather than a wave of 500s. ## How I would decide For a public or multi-client API, or anything returning user data: yes, a rule with a CI check. For a small internal service whose only consumer is one frontend in the same repository, the documentation half matters less, but the filtering half still prevents the leak nobody planned, so I would still adopt it, with the exemptions written down.
- Which FastAPI endpoints would you exempt from a mandatory response model rule?Those that deliberately return a `Response`: file downloads, redirects, HTML pages and streams, where there is no JSON body to filter. They should still document what they return through `response_class` or the `responses` parameter, so `/docs` and generated clients are not left guessing.
- How would you roll the rule out on an existing FastAPI codebase without a wave of 500s?Start with endpoints that return stored objects, since those leak first. Add their models, run the full suite and watch staging logs for response validation errors, because a model stricter than the real data turns into 500s. Fix the model or the data, and only then enable the CI check.
A response model is the packing list at the warehouse door: only items on the list leave, and a new item on the shelf stays there until someone adds it to the list.
- Without a response model FastAPI still drops fields the docs do not show
- A return value missing a declared field is sent as it is
- Response models are documentation only
- Declaring response models everywhere makes FastAPI 0.143 slower
- File downloads and redirects must also declare a JSON response model
Assumes FastAPI 0.143; the one-pass Pydantic serialization for declared response models arrived in 0.130.