REST Design and Errors

Finish the REST picture with create, update and delete, then make errors something a caller can rely on: your own exception classes for the problems your API knows about, and one error shape for every error, whoever raised it. Then you'll run a bike repair shop's work tickets through their whole life.

Updated

Create, Update and Delete

  1. Create, Update and Delete: POST, PUT, PATCH and DELETE (Journeyman): A FastAPI resource is finished with four routes that change it, POST that answers 201 with the new item, PUT that replaces a whole item, PATCH that changes only the fields sent with model_dump(exclude_unset=True), and DELETE that answers 204 with no body, each answering 404 when the item isn't there.

Errors Everyone Can Read

  1. Raising Your Own Exceptions in an API (Journeyman): An API's own rules raise exception classes named for each problem, such as TicketNotFound and StatusChangeNotAllowed, from plain functions that know nothing about HTTP, and @app.exception_handler turns each one into a status code and a JSON body, such as 404 or 409.
  2. One Error Shape for the Whole API (Journeyman): Every error an API sends can have one JSON shape, modeled on RFC 9457's problem details (a status, a title, a detail sentence and, on a 422, a list of field problems), built by one problem() function and sent by an exception handler for each kind of error, FastAPI's own 404 and 422 included, with a catch-all that answers a crash with a calm 500 and never a traceback.

Exercise: Bike Repair Tickets

  1. Exercise: Bike Repair Tickets (Journeyman): Finish a bike shop's FastAPI tickets API with a PATCH that changes only what's sent, a status change that moves one step at a time and answers 409 through your own exception and its handler, a DELETE that answers 204, and handlers that give every error, FastAPI's own 404 and 422 and a crash included, one JSON shape.