Document Error Responses
Exit

Document Error Responses

Add response models and error documentation to the get, delete, and update endpoints

💻

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

The missing documentation

Open the /docs page and look at the GET /expenses/{expense_id} endpoint. The response section shows a generic "Successful Response" with no schema. A client developer cannot tell what fields to expect.

Worse, there is no mention of the 404 error. The client has no way to know that passing an invalid identifier returns {"detail": "Expense not found"} unless they test it manually.

Adding response_model and responses together

You can combine both parameters in a single decorator:

@app.get("/expenses/{expense_id}",
         response_model=ExpenseOut,
         responses={404: {"model": ErrorResponse}})

  • response_model documents the successful response shape
  • responses documents additional status codes and their shapes

The /docs page then shows a complete contract: the 200 response returns an ExpenseOut object, and a 404 response returns an ErrorResponse object.

Three endpoints raise 404 errors: get, delete, and update. You will add both parameters to all three.

Instructions

Add response_model and responses to the three endpoints that raise 404 errors.

  1. Add response_model=ExpenseOut and responses={404: {"model": ErrorResponse}} to the @app.get("/expenses/{expense_id}") decorator.
  2. Add response_model=ExpenseOut and responses={404: {"model": ErrorResponse}} to the @app.delete("/expenses/{expense_id}") decorator.
  3. Add response_model=ExpenseOut and responses={404: {"model": ErrorResponse}} to the @app.patch("/expenses/{expense_id}") decorator.