Exercise: Movie Night Picker
Finish Movie Night Picker, an API that asks a showtimes service and a reviews service at the same time with httpx and asyncio.gather, answers 503 when either is slow or down, and saves the group's pick with a 201 before posting it to the group chat in a background task, checked by tests that never touch the network.
Freelancer · FastAPI · REST API · Updated
A group of friends meets for a movie every Friday, and every Friday the group chat fills with "what's on?" and "is it any good?". You'll finish Movie Night Picker, the API that settles it: it asks a showtimes service what's on tonight and a reviews service how good each film is, at the same time, and suggests the best one. When a service is slow or down it says so honestly, and when the group picks a film it answers at once and posts the pick to the group chat afterward. It's built the way this chapter built it, and tests check every answer without touching the network.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-movie-night-picker, 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-movie-night-picker.git
Git makes a folder, exercise-fastapi-movie-night-picker, 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/tonight.py:GET /tonight, for you to write.routers/picks.py: the group's picks.GET /picksand thePickInmodel are ready;POST /picksis for you to write.services.py: the two services' addresses,ServiceDown(the exception for a service that isn't answering),make_client()(the httpx client the routes use, which needs a timeout from you) andget_client()(the dependency a route gets its client from).main.py: makes the app, adds the routers, and holds the error handlers from One Error Shape for the Whole API, with one more:ServiceDownanswers 503. Ready to use.stand_ins.py: stand-ins for the showtimes and reviews services, each taking a second to answer, so you can try the API on your own computer. Ready to use.chat.py: a stand-in for the group chat,post_to_group_chat(pick), which takes two seconds and prints its message in the terminal. Ready to use.data.py: the group's picks, in the listPICKS, andreset_picks(), which the tests use to empty it before each test.tests/test_movie_night.py: the tests. You don't need to change it.requirements.txtandpytest.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 comments at the top of routers/tonight.py and routers/picks.py list every request the API should answer:
GET /tonight 200, the best-reviewed film showing tonight, its showtime with its stars added. With the
stand-ins' answers it's {"film_id": 3, "title": "Robot Garden", "time": "20:15", "stars": 4.7}:
film 5 has more stars, 4.9, but isn't showing tonight, and film 4 has no review yet.
Two films with the same stars: the one that starts first, earlier in the showtimes list.
404 when no film showing tonight has a review:
detail "No film showing tonight has a review yet."
503 when a service can't be reached, takes more than two seconds, or answers 400 or more:
detail "The reviews service isn't answering. Try again in a few minutes."
(or "The showtimes service ...", naming the service that failed)
GET /picks 200, every pick saved so far (ready)
POST /picks 201, the new pick. For the body {"film_id": 3, "picked_by": "Rosa"} the answer is
{"id": 1, "film_id": 3, "picked_by": "Rosa"}: its id is one more than the number of picks saved.
After the answer has gone, a background task posts the pick to the group chat.
422 when a field is missing, such as a body with no picked_by.
Every error comes back in the API's one shape, such as {"status": 503, "title": "Service Unavailable", "detail": "..."}.
- Give the client a timeout. In
services.py, makemake_clientgive itshttpx.AsyncClienta timeout of 2 seconds, keeping thetransportit's handed. - Ask one service. In
routers/tonight.py, write a helperasync def ask(client, service, url)that gets the service's answer, raises an error for an error status, and gives back its JSON. When httpx raises any of its errors, raiseServiceDown(service)instead. - Ask both at once. Write
GET /tonightas anasync defroute that takesclient: Annotated[httpx.AsyncClient, Depends(get_client)]and awaitsaskfor both services together withasyncio.gather. - Pick the film. Turn the reviews into a dictionary of stars by
film_id, then find the showtime with the most stars, and answer 404 withHTTPExceptionwhen there's none. - Save the pick, then tell the chat. In
routers/picks.py, writePOST /picks: answer 201 with the new pick, and addpost_to_group_chatas a background task with the pick.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
At first all 12 tests fail. That's expected: 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 /tonight should answer 200, but it answered 404 with {"status":404,"title":"Not Found","detail":"Not Found"}.
No server needs to be running, not even the stand-ins. Each test hands the app a client built by your make_client with a stand-in transport, httpx's MockTransport: a function in the test file that answers the app's requests to the services, so nothing leaves your computer. One test's stand-in services answer only once both questions have arrived, so it passes only when GET /tonight asks both at the same time. Others make a service answer 500, refuse to connect or take too long, and one makes the group chat fail, to check that the 201 has already gone by then.
To try the API yourself, start the stand-ins in one terminal with fastapi dev stand_ins.py --port 8001, then the API in a second terminal with fastapi dev main.py, and open http://127.0.0.1:8000/docs. Stop each with Ctrl+C. The README has the details.
Hints
- The timeout goes on the client.
httpx.AsyncClient(timeout=2.0, transport=transport), as in Async Routes: When They Help, and When They Don't. - One helper knows which service failed. Put the
tryinsideask, aroundawait client.get(url)andresponse.raise_for_status(), withexcept httpx.HTTPError. Atryaround the wholeasyncio.gathercan't tell the two services apart. asyncio.gathergives the results back in order.showtimes, reviews = await asyncio.gather(ask(...), ask(...)), as in async and await in Plain Words.- Replace the best film only when another has more stars. Then the first of two films with the same stars stays the best, and it's the one that starts first.
- Pass the function, don't call it. Work That Runs After the Response shows
background_tasks.add_task(post_to_group_chat, pick); withpost_to_group_chat(pick)inside, the caller waits for the chat, and the test with the chat down gets a 500.
When you're done
Every test is green: pytest's last line says 12 passed. With the stand-ins running, GET /tonight on the docs page answers 200 after about a second, not two:
{"film_id":3,"title":"Robot Garden","time":"20:15","stars":4.7}
POST /picks with {"film_id": 3, "picked_by": "Rosa"} answers 201 at once, and two seconds later the API's terminal shows:
Group chat: Rosa picked film 3 for tonight.
Now stop the stand-ins with Ctrl+C and send GET /tonight again. It answers 503 Service Unavailable:
{"status":503,"title":"Service Unavailable","detail":"The showtimes service isn't answering. Try again in a few minutes."}
Then look back at POST /picks. If the group chat message had to arrive every time, even after the server restarted, what would you use instead of BackgroundTasks?
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-fastapi-movie-night-picker), 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-fastapi-movie-night-picker.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-fastapi-movie-night-picker, 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
Asking several services at once, answering honestly when one fails, and doing slow work after the answer are what keep a real API quick when it depends on other people's servers, and you've now done all three with tests that never touch the network.