Why Response Models Matter
Understand how response models define a clear contract between your API and its clients
The problem with untyped responses
Right now, every endpoint in your API returns a plain dictionary. The code works, but the automatic documentation at /docs shows the response as a generic object. A client developer reading that page has no way to know the exact fields, types, or optional values your API returns.
This creates real problems. A frontend developer might guess that the amount field is a string instead of a float. A mobile developer might not realize the date field can be null. Every team that consumes your API has to read your source code or test endpoints manually to figure out the response shape.
What a response model does
A response model is a Pydantic class that describes the exact shape of your API's response. You attach it to a route decorator with the response_model parameter:
@app.get("/expenses", response_model=list[ExpenseOut])
def list_expenses():
...This gives you two benefits:
- Accurate documentation: The
/docspage shows every field name, type, and default value for the response. Client developers get a precise contract without reading your code. - Automatic validation: FastAPI checks that your response matches the model before sending it. If your code accidentally returns an extra field or a wrong type, FastAPI catches it.
Documenting error responses
By default, the /docs page only shows the successful response. But most endpoints can also return errors. When a client requests an expense that does not exist, your API returns a 404 status with a {"detail": "Expense not found"} body.
FastAPI lets you document these error cases with the responses parameter:
@app.get("/expenses/{expense_id}",
response_model=ExpenseOut,
responses={404: {"model": ErrorResponse}})The /docs page then shows both the success response and the 404 error response, each with its exact shape.
What you will build next
In the next three chapters, you will add response models to every endpoint, document error responses for endpoints that raise 404 errors, and build a spending summary endpoint as a capstone feature.