Exercise: Bike Repair Tickets

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.

Journeyman · FastAPI · REST API · Updated

By

Spoke & Chain Bike Repair's front desk and its mechanics' phones share one tickets API. Listing, reading and adding tickets already work. You'll finish the rest of a ticket's life: fix its details, move it along from waiting to picked up one step at a time, delete it, and make every error the API sends, FastAPI's own included, come back in the one shape this chapter built. Tests check every answer as you go.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-bike-repair-tickets, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:

cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-bike-repair-tickets.git

Git makes a folder, exercise-fastapi-bike-repair-tickets, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment. On Windows (PowerShell):

python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt

On a Mac (zsh):

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

The prompt starts with (.venv) once the virtual environment is on. The exercise's README says what each command does, and what to do if PowerShell won't run the second one.

The folder holds:

  • routers/tickets.py: the tickets router, for you to finish. GET /tickets, GET /tickets/{ticket_id} and POST /tickets are ready.
  • shop.py: the shop's rules, in plain Python. TicketNotFound, find_ticket and NEXT_STEP are ready; StatusChangeNotAllowed and change_status are yours to write.
  • main.py: makes the app, adds the routers, and holds the error handlers, for you to finish. One handler is there, in the old {"detail": ...} shape.
  • routers/report.py: GET /report, the end-of-day report, which crashes on purpose, so your catch-all handler has a real crash to handle.
  • data.py: the shop's five tickets, in the list TICKETS, with next_id() and reset_tickets(), which the tests use to put the tickets back before each test.
  • tests/test_tickets.py: the tests, which send requests to your app with TestClient. You don't need to change it.
  • requirements.txt and pytest.ini: the packages the app and the tests need, at exact versions, and where pytest finds the tests and your code.

What to do

The comment at the top of routers/tickets.py lists every request the router should answer, and the one at the top of main.py describes the error shape and what each error answers. The new requests:

PATCH  /tickets/1           Changes only the fields the body sends: any of customer, bike and problem, each text.
                            For {"problem": "flat front and rear tires"}: 200, ticket 1 with that problem and
                            everything else as it was. {} changes nothing. Any other field, such as status, is ignored.
                            422 when a field sent isn't text, such as {"bike": 7}.
PATCH  /tickets/1/status    Body {"status": "in repair"}, one of "waiting", "in repair", "ready" or "picked up".
                            200, ticket 1 with its new status, when it's the ticket's next step.
                            409 otherwise: detail "Ticket 1 is waiting, so it can't go to ready."
                            422 when status isn't one of the four, such as {"status": "fixed"}.
DELETE /tickets/3           204, no body, and ticket 3 is gone.
Any of them, /tickets/99    404, detail "There's no ticket 99."

And every error, from any route, in the one shape. Five of them:

GET /tickets/99    404  {"status": 404, "title": "Not Found", "detail": "There's no ticket 99."}
POST /tickets {}   422  {"status": 422, "title": "Unprocessable Content", "detail": "The request isn't valid.",
                         "problems": [{"field": "customer", "message": "Field required"},
                                      {"field": "bike", "message": "Field required"},
                                      {"field": "problem", "message": "Field required"}]}
GET /tickets/abc   422  the same detail, with one problem: the field ticket_id
GET /bikes         404  {"status": 404, "title": "Not Found", "detail": "Not Found"}
GET /report        500  {"status": 500, "title": "Internal Server Error", "detail": "Something went wrong on our side."}
  1. Write the shop's rule. In shop.py, the exception class StatusChangeNotAllowed and change_status(ticket, new_status), which moves a ticket one step along or raises StatusChangeNotAllowed with the message above. Then import them where the comments in routers/tickets.py and main.py say.
  2. PATCH a ticket's details with PATCH /tickets/{ticket_id}, changing only the fields the body sends.
  3. PATCH a ticket's status with PATCH /tickets/{ticket_id}/status, through find_ticket and change_status.
  4. DELETE a ticket with DELETE /tickets/{ticket_id}, answering 204 with no body.
  5. Give every error one shape in main.py: a problem() function, the TicketNotFound handler changed to use it, and a handler each for StatusChangeNotAllowed (409), RequestValidationError (422 with problems), Starlette's HTTPException and Exception (500).

Check your work

Run the tests from the exercise folder, with the virtual environment on:

pytest

No server needs to be running: TestClient hands each request straight to the app. At first 22 of the 23 tests fail. That's expected: test 1 passes because listing is ready, and each part you finish turns its tests green. A failing test's message says what it sent, what it expected and what came back, for example GET /tickets/99 should answer the one error shape, with exactly status, title, detail, but it answered {'detail': "There's no ticket 99."}.

To try the API yourself, start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. Try it out sends each route a real request. GET /report shows its whole error in the terminal, while the caller gets the calm 500. Stop the server with Ctrl+C.

Hints

  • Start in shop.py. It's the Do It from Raising Your Own Exceptions in an API: NEXT_STEP.get(ticket["status"]) is the next step, or None for a ticket that's picked up.
  • PATCH needs every field optional. A model whose fields are all str | None = None, then model_dump(exclude_unset=True), as Create, Update and Delete: POST, PUT, PATCH and DELETE shows. Fields the model doesn't list, such as status, are left out for you.
  • The status body is a model too, with Literal for the four statuses, so FastAPI answers "fixed" with a 422 before your route runs.
  • status_code=204 goes on the DELETE route's decorator, and the route returns nothing.
  • Write problem() first, as One Error Shape for the Whole API does: HTTPStatus(status).phrase is the title, and every handler becomes a line or two. Register the HTTPException handler for StarletteHTTPException, already imported in main.py, or /bikes keeps FastAPI's own shape.
  • The 500's detail is always the same sentence. Never put the exception's own message in it.

When you're done

Every test is green: pytest's last line says 23 passed. And on the docs page, PATCH /tickets/{ticket_id}/status for ticket 1 with {"status": "ready"} answers 409 with:

{"status":409,"title":"Conflict","detail":"Ticket 1 is waiting, so it can't go to ready."}

Then send {"status": "in repair"} and {"status": "ready"} in turn: both answer 200, and Dana's bike is ready to pick up.

Now look back at shop.py. If the shop wanted a ticket to go back from ready to in repair, say when a customer finds the brakes still squeal, how many lines would change, and would any route or handler change at all?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-fastapi-bike-repair-tickets), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-fastapi-bike-repair-tickets.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-fastapi-bike-repair-tickets, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

A resource that can be created, changed and deleted, rules that live in plain Python, and errors that all look the same are what a front end needs from an API, and you've now built all three with tests that prove each one.

Key terms

Related