Skip to content
tezvyn:

FastAPI: Documenting Additional API Responses

Source: fastapi.tiangolo.comMediumHow cards are made

FastAPI: Documenting Additional API Responses

Document every possible API response, not just the happy path. The responses decorator parameter lets you define alternative status codes and schemas, like a 404 error model, making your OpenAPI docs complete.

Why it exists

By default, FastAPI documents the single success response defined by response_model. But real-world APIs have multiple outcomes: an item not found (404), invalid input (422), or a request accepted for later processing (202). Defining additional responses makes your API contract explicit and machine-readable via OpenAPI, improving documentation and client generation.

The mental model

Think of your API documentation as a contract. The response_model defines the "happy path" clause. The responses parameter lets you add appendices for all the "what if" scenarios, like "What if the ID doesn't exist?" or "What if the data is malformed?". Each appendix specifies the exact status code and the shape of the data the client will receive in that scenario.

How it works

In your path operation decorator (e.g., @app.get), you pass a responses dictionary. The keys are status codes (as strings or integers), and the values are dictionaries describing that response, often including a Pydantic model. When your code logic needs to return one of these alternative responses, you must manually construct and return a Response object, like JSONResponse(status_code=404, content={"message": "Item not found"}).

When to use it

Use this whenever an endpoint can return more than one status code with a structured body. A common case is defining a specific schema for 404 Not Found errors instead of relying on a generic HTTP exception. It's also useful for non-200 success codes, like a 202 Accepted response for an asynchronous job, ensuring clients know what to expect.

When not to use it

For simple endpoints that only ever succeed or fail with a standard, undocumented error, this is overkill. If you are just starting with FastAPI and your primary goal is a functional happy path, you can defer this until your API needs to be consumed by other teams or automated tools that rely on a strict OpenAPI specification.

One canonical example

Imagine an endpoint /items/{item_id}. You can document both the success and not-found cases. In the decorator: @app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}}). Inside the function, if the item exists, you return item. If it does not exist, you must explicitly return JSONResponse(status_code=404, content={"message": "Item not found"}). Simply returning the dictionary would incorrectly send a 200 OK status, violating your API's documented contract.

Interview question

When a FastAPI endpoint documents a 404 response using the "responses" parameter, what is essential for the API to correctly return that 404 status code and its defined schema?

  • a.The function must explicitly return a Response object with the 404 status code and content.Correct
  • b.Raising an HTTPException with status code 404 is the only way to trigger the documented response.
  • c.The "responses" parameter automatically changes the HTTP status code when the associated model is returned.
  • d.FastAPI infers the 404 status code if the returned dictionary matches the documented 404 model.
Why?

The "responses" parameter only documents the API contract; it does not alter runtime behavior. To return a specific status code and body, you must manually construct and return a Response object like JSONResponse. Simply returning a dictionary will default to a 200 OK status, even if a 404 model is documented.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles