Exercise: Book Club's First Route
Write a book club's first FastAPI app, a route that lists every book and a route that finds one book by its number or answers 404, then write two TestClient tests of your own and let pytest check it all.
Apprentice · Python · FastAPI · Updated
Chapter & Verse, the book club, has its list of books and an app designer waiting for an API. You'll write it with FastAPI: one route that answers with every book, and one that answers with a single book by its number, or a 404 when the club has no such book. Then you'll write two tests of your own, the way back-end developers prove a route works, and let pytest run them with the tests that come with the exercise.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-python-book-club-first-route, 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-python-book-club-first-route.git
Git makes a folder, exercise-python-book-club-first-route, 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, the same three steps as in the exercises before. 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. FastAPI brings a few packages of its own, so the install takes a minute.
The folder holds:
main.py: the app, with the club's four books inBOOKS, and two functions for you to finish.tests/test_books.py: seven tests that send requests to your app with TestClient and check what comes back. You don't need to change it.tests/test_your_tests.py: two tests for you to write.try_routes.py: sends four requests to your app and prints each answer. Ready to use.requirements.txtandpytest.ini: the packages (FastAPI with its standard extras, which include what TestClient needs, httpx, and pytest, each at an exact version), and where pytest finds the tests and your code.
What to do
main.py already makes the app and holds the books. Its two functions aren't tied to an address yet, and each one stops with a NotImplementedError that says Not built yet. The docstring under each says what it should answer, with examples:
def list_books():
"""Answer GET /books with every book in BOOKS, in the order they're listed.
Tie this function to GET /books with a decorator line right above it.
GET /books -> 200, a JSON list of all 4 books, The Lantern Keeper's Cat first
"""
raise NotImplementedError("Not built yet.")
list_books(): add the decorator line that ties it to GET requests for/books, and replace theraiseline so it returnsBOOKS.get_book(book_id): add the decorator line for/books/{book_id}, givebook_idthe type hintint, and replace theraiseline so it returns the book whose"id"isbook_id. When no book has that id, it raisesHTTPExceptionwith the status code404and the detail"Book not found". For example,/books/2answers with Twelve Bridges North,/books/42answers 404 with{"detail": "Book not found"}, and/books/abcgets FastAPI's 422 once the type hint is there.- Your two tests, in
tests/test_your_tests.py. Replace each test'sraiseline with a test that sends its request withclient.getand checks two things, as its docstring says:test_8_get_book_3_is_rain_over_copper_hill:/books/3answers with the status code200, and the book's"title"is"Rain over Copper Hill".test_9_get_book_99_answers_404_book_not_found:/books/99answers with the status code404, and its JSON is{"detail": "Book not found"}.
Keep the function names, BOOKS and the addresses as they are.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 9 tests fail. That's expected: each route you finish turns its tests green, and so does each test you write. A failing test in test_books.py says what it asked for, what it expected and what came back, for example GET /books (status code) should answer 200, but it answered 404. A 404 for /books means the app has no route for that address yet.
To see your app's answers, run python try_routes.py. To try it in the browser, run fastapi dev main.py, open http://127.0.0.1:8000/docs, use Try it out on each route, and press Ctrl+C in the terminal to stop the app when you're done.
Hints
- A route is two things: a decorator line and the function right below it. Your First FastAPI Route shows both routes in the book club's app.
- The name in the braces and the parameter's name must match, or FastAPI can't tell where
book_idcomes from. - Check the type hint first if every book answers 404. Without it,
book_idis the text"2", which never equals the number2. - Raise after the loop, not inside it. A loop can return a book as soon as one matches; only when the loop ends without a match is the book missing.
- Your tests look like the ones in
test_books.py, written with plainassert: send the request, checkresponse.status_code, then checkresponse.json(). Testing a Route shows a test for each.
When you're done
Every test is green: pytest's last line says 9 passed. And python try_routes.py prints:
Chapter & Verse: what the app answers
GET /books -> 200
[{"id":1,"title":"The Lantern Keeper's Cat","pages":312,"status":"read"},{"id":2,"title":"Twelve Bridges North","pages":284,"status":"read"},{"id":3,"title":"Rain over Copper Hill","pages":356,"status":"read"},{"id":4,"title":"The Orchard Ledger","pages":241,"status":"reading"}]
GET /books/2 -> 200
{"id":2,"title":"Twelve Bridges North","pages":284,"status":"read"}
GET /books/42 -> 404
{"detail":"Book not found"}
GET /books/abc -> 422
{"detail":[{"type":"int_parsing","loc":["path","book_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}
Now look at your test for book 99. Would it still pass if get_book answered 404 for every book, even the ones that are there? It would, which is why test_books.py also asks for books that exist: a "not there" test proves something only next to a test that finds one.
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.
On GitHub, click +, then New repository. Name it (for example
exercise-python-book-club-first-route), choose Public, and click Create repository. Leave out the README: your folder already has one.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-python-book-club-first-route.git git add . git commit -m "My solution" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-python-book-club-first-route, 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
Two routes and the tests that prove them are the whole shape of a web API in miniature: every API you'll build later is more routes like these, each with its tests.