Exercise: Board Game Shelf API

Finish the board game café's FastAPI games router, which lists the shelf with filters for group size and playing time, finds one game by its id with a 404 when there's none, and adds a game with a 201, and let TestClient's tests check every answer.

Apprentice · FastAPI · REST API · Updated

By

The Rolling Dice board game café keeps getting the same questions at the door: "Do you have something for four of us?", "Anything quick?". You'll finish the café's API so its staff app can answer them: a games router that lists the shelf with filters for group size and playing time, finds one game by its id, and adds a game a regular has donated. It's built with FastAPI, the way this chapter built the café's API, and tests check every answer as you go.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-board-game-shelf-api, 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-board-game-shelf-api.git

Git makes a folder, exercise-fastapi-board-game-shelf-api, 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/games.py: the games router, for you to finish.
  • main.py: makes the app and adds the games router with app.include_router. Ready to use.
  • data.py: the café's eight games, in the list GAMES, and reset_games(), which the tests use to put the shelf back before each test.
  • tests/test_games.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

routers/games.py imports what you need and makes router, with no prefix and no routes yet, so for now every request answers 404. The comment at its top lists every request the API should answer:

GET /games                           200, every game in data.py
GET /games?players=4                 200, only the games made for a group of 4 (min_players 4 or fewer
                                     and max_players 4 or more): games 1, 2, 4 and 6
GET /games?max_minutes=30            200, only the games that take 30 minutes or less: games 2, 3, 5 and 6
GET /games?players=4&max_minutes=30  200, only the games that pass both filters: games 2 and 6
GET /games?players=12                200, an empty list, []: no game is made for a group of 12
GET /games?players=four              422, FastAPI's own answer: players is a whole number
GET /games/4                         200, game 4 (every game's id works the same way)
GET /games/99                        404, {"detail": "There's no game 99."}
GET /games/chess                     422, FastAPI's own answer: a game's id is a whole number
POST /games                          201, the new game, kept on the shelf. For the body
                                     {"title": "Lantern Festival", "min_players": 2, "max_players": 4, "minutes": 35}
                                     the answer is {"id": 9, "title": "Lantern Festival", "min_players": 2,
                                     "max_players": 4, "minutes": 35, "available": true}: its id is one more
                                     than the number of games on the shelf, and a new game is always available
POST /games, a body with no minutes  422, FastAPI's own answer: the body needs all four fields

The docs page lists these routes under the heading games, and the list's address is exactly /games, with no slash at the end.

  1. Set up the router. Give router the prefix /games and the tag games.
  2. List the games with GET /games, with the players and max_minutes filters, each used only when the request sends it.
  3. Find one game by its id, such as GET /games/4, or answer 404 with a detail that names the id when no game has it.
  4. Add a game with POST /games: describe the body with a small model, build the new game with its id and "available": True, add it to GAMES, and answer 201 with it.

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 all 13 tests fail. That's expected: each request you answer turns its test green. A failing test's message says what it sent, what it expected and what came back, for example GET /games/4 should answer 200, but it answered 404 with {"detail":"Not Found"}.

To try the API yourself, start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. Each route you add appears there under games; Try it out sends it a real request. Stop the server with Ctrl+C.

Hints

  • The prefix goes on the router, not on each route. With prefix="/games", the list's own path is the empty string "" and one game's is "/{game_id}", as Organizing Routes with APIRouter shows. A path of "/" puts the list at /games/ instead, and the last test says so.
  • A default of None makes a filter optional. Query Parameters: Filters and Options checks each filter with is not None and skips a game with continue as soon as one sent filter rules it out.
  • Let the type hints do the 422s. With game_id: int and players: int | None = None, FastAPI answers chess and four itself, before your function runs (Path Parameters and Their Types).
  • Raise the 404, don't return it. When It Isn't There: HTTPException and 404 shows why a returned HTTPException answers 200.
  • Count the shelf for the new id. Taking JSON In: Your First Request Body builds a new game with len(GAMES) + 1, **new_game.model_dump() and "available": True, and status_code=201 goes on the route's decorator.

When you're done

Every test is green: pytest's last line says 13 passed. And on the docs page, POST /games with Lantern Festival's body answers 201 with:

{"id":9,"title":"Lantern Festival","min_players":2,"max_players":4,"minutes":35,"available":true}

Then GET /games?players=4&max_minutes=40 answers with games 2, 6 and 9: Lantern Festival is on the shelf, and it fits a group of four in 35 minutes.

Now look back at your filters. If the café asked for a third one, available, how many lines would you add, and would any of the lines you have now change?

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-board-game-shelf-api), 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-board-game-shelf-api.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-board-game-shelf-api, 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

Path and query parameters, a 404 when something's missing, a 201 when something's made, and a router per resource are the bones of nearly every REST API, and you've now built them all in one small app with tests that prove each one.

Key terms

Related