Add Response Models
Exit

Add Response Models

Create ExpenseOut and ErrorResponse models and attach them to your endpoints

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Defining the response shape

Your stored expense dictionaries have five fields: id, description, amount, category, and date. The ExpenseOut model mirrors this shape as a Pydantic class. FastAPI uses it to validate outgoing data and generate documentation.

You already have an Expense model for input validation. ExpenseOut is separate because the response includes an id field that the client never sends — the server generates it.

The ErrorResponse model

Error responses from HTTPException always have a detail field. Defining an ErrorResponse model with detail: str gives FastAPI a schema to document these errors on the /docs page.

Attaching a response model

Add response_model=ExpenseOut to a decorator to tell FastAPI the response shape for that endpoint:

@app.post("/expenses", status_code=201, response_model=ExpenseOut)

For endpoints that return a list, wrap the model in list[]:

@app.get("/expenses", response_model=list[ExpenseOut])

Instructions

Add two new model classes after ExpenseUpdate and before save_expenses. Then attach response models to the create and list endpoints.

  1. Create a class named ExpenseOut that inherits from BaseModel with five fields: id as int, description as str, amount as float, category as str, and date as Optional[str] with a default of None.
  2. Create a class named ErrorResponse that inherits from BaseModel with one field: detail as str.
  3. Add response_model=ExpenseOut to the @app.post("/expenses", status_code=201) decorator.
  4. Add response_model=list[ExpenseOut] to the @app.get("/expenses") decorator.