In FastAPI, how do you document a 404 error body and other extra responses that response_model does not describe?
answer
- a dict keyed by status code
- one key FastAPI adds itself
- documentation, not enforcement
- a deep merge for the rest
basics
~20 sPass responses={404: {"model": Message, "description": "..."}} to the decorator, an APIRouter or include_router. FastAPI turns model into a JSON Schema reference but never validates that response, so the body you return must match it yourself.
solid answer
~40 s`response_model` and `status_code` describe only the main response. For the others, the decorator, `APIRouter` and `include_router` accept `responses`, a dict keyed by status code whose values are OpenAPI response objects plus one FastAPI-only key, `model`, which becomes a `$ref` under `content` for the response class's media type, usually `application/json`. In FastAPI 0.143 an entry without a `description` gets the HTTP reason phrase, so 404 reads "Not Found". It is documentation only: the 404 body is not validated or filtered, so you return a `JSONResponse` that matches, or document the `{"detail": ...}` shape `HTTPException` sends. Router-level entries merge with the operation's own. What `responses` cannot express, such as an `x-` extension or a body you parse yourself, goes in `openapi_extra`, deep-merged into the generated operation last.
code
python · 35 linesfrom fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
class NotFound(BaseModel):
detail: str
app = FastAPI()
ITEMS = {1: Item(id=1, name="Plumbus")}
@app.get(
"/items/{item_id}",
response_model=Item,
responses={404: {"model": NotFound, "description": "No item with this id"}},
openapi_extra={"x-internal-owner": "catalogue"},
)
def read_item(item_id: int):
if item_id not in ITEMS:
# Not validated against NotFound: keep the body in line yourself.
return JSONResponse(status_code=404, content={"detail": "Item not found"})
return ITEMS[item_id]
op = app.openapi()["paths"]["/items/{item_id}"]["get"]
print(sorted(op["responses"])) # ['200', '404', '422']
print(op["responses"]["404"]["description"])
print(op["x-internal-owner"])go deeper
Know that responses on the decorator adds extra status codes to the docs, and that model there works like response_model.
Explain how model becomes a schema reference, how entries merge with the main response and with router-level ones, and when FastAPI adds its own 422.
Stress that extra responses are unenforced: keep error models matching what handlers send, because generated clients decode exactly what the schema promises.
Set a shared error contract for the team, declared once on routers, so every service documents the same failure shapes the same way.
## What response_model leaves out A path operation's `response_model` (or return annotation) and `status_code` describe one response: the success case. Real endpoints also answer `404`, `409` or `403`, sometimes return an image instead of JSON, and carry headers. FastAPI cannot infer those from your code, because they usually come from a raised exception or a `Response` you return directly. You declare them with **`responses`**. ## The responses parameter `responses` is a dict keyed by status code (an `int`, or a range string such as `"4XX"`, or `"default"`). Each value is an OpenAPI response object, with one extra key FastAPI understands: | Key | Meaning | |---|---| | `model` | a Pydantic model; FastAPI generates its JSON Schema and references it (FastAPI-only, removed from the output) | | `description` | the human text for that response | | `content` | media types and their schemas or examples, for example `{"image/png": {}}` | | `headers` | response headers to document | It is accepted on the path operation decorator, on `APIRouter(responses=...)` and on `include_router(..., responses=...)`. Router-level entries are merged with the operation's own, which is how a team declares a shared `401` or `404` once. ## What FastAPI does with it 1. For an entry with `model`, it adds the model to `components/schemas` and puts a `$ref` under `content`, using the route's response class media type, normally `application/json`. 2. Without a `description`, FastAPI 0.143 uses the HTTP reason phrase for that code, so `404` reads "Not Found"; only a code with no known phrase gets "Additional Response". Some docs examples still show the older text. 3. An entry for the main status code is **merged** with the generated one, so you can add an `example` or a second media type to the `200` without losing the `response_model` schema. 4. FastAPI adds its own `422` "Validation Error" to any operation with parameters or a body, unless `responses` already declares `422`, `"4XX"` or `"default"`. For `responses={404: {"model": NotFound}}` on a JSON route, the operation in the schema gains this entry, and `NotFound` joins the shared component schemas: ```json "404": { "description": "Not Found", "content": { "application/json": {"schema": {"$ref": "#/components/schemas/NotFound"}} } } ``` Because the model is referenced rather than inlined, several operations that declare the same error model share one component, and a generated client gets one error type instead of a copy per endpoint. ## Documentation is not enforcement - **The extra response is not validated.** `response_model` filtering and validation apply to the value the function returns normally. A `JSONResponse` you return is sent as is, so a `404` body with the wrong fields reaches the client while the schema claims otherwise. - **Match what your errors really send.** `HTTPException(status_code=404, detail="...")` produces `{"detail": "..."}`; a documented model with a `message` field would misdescribe it. Keep error models next to the handlers that produce them. - **A generated client trusts the schema.** It will decode a `404` with the declared model, so a mismatch shows up as a client bug, not a server error. ## Reuse Shared entries are plain dicts, so FastAPI's docs reuse them with unpacking: define `common = {404: {"description": "Not found"}}` and pass `responses={**common, 409: {...}}`. For a whole router, put them on `APIRouter(responses=...)`: - A `401` that every operation of an authenticated router can return is declared once on the router, and FastAPI adds it to each operation's entries. - An operation that needs one more code, such as a `409` on create, declares only that one in its own `responses`. - Headers belong in the same entry: a `429` can document a `Retry-After` header under `headers`, so clients know to read it. Declaring errors once per router also keeps their descriptions consistent, which matters more to a reader of the docs than any single wording. ## openapi_extra for everything else `openapi_extra` is the low-level escape hatch on a single path operation. Its dict is **deep-merged** into the generated operation after everything else, so it can add or override any part: - vendor extensions such as `{"x-internal-owner": "catalogue"}`; - a `requestBody` description when the endpoint reads `await request.body()` itself, for instance YAML, so FastAPI has no body parameter to describe; FastAPI's docs build that schema with the model's `model_json_schema()`; - small corrections to a generated parameter. Reach for `responses` first: it understands `model`, merges with the main response, and is what other readers expect. Use `openapi_extra` for what it cannot express.
- In FastAPI, how do you document that one path operation can return either JSON or a PNG image?Add a second media type to the main status code: `responses={200: {"content": {"image/png": {}}}}`. FastAPI merges it with the generated `application/json` entry, so the `200` lists both. Returning the image is still your code's job, for example with a `FileResponse`.
- In FastAPI, why might a team declare the 422 response itself in responses?If a custom `RequestValidationError` handler returns a different body, the automatic `422` entry pointing at `HTTPValidationError` would be wrong. Declaring `422`, or a `"4XX"` or `"default"` entry, stops FastAPI adding its own, so the schema describes the body the handler really sends.
- Declaring responses={404: {"model": ...}} makes FastAPI validate the 404 body.
- The model key is part of the OpenAPI response object itself.
- Extra responses can only be declared per decorator, never on a router.
- openapi_extra replaces the generated operation instead of merging into it.
- FastAPI cannot document any status code other than the main one.
Assumes FastAPI 0.143, where an extra response without a description takes the HTTP reason phrase; older docs examples show Additional Response instead.