# 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 November 19, 2026

By Gregor Dzierzon

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](https://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:

```bash
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):

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

On a Mac (zsh):

```bash
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 /picks` and the `PickIn` model are ready; `POST /picks` is 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) and `get_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: `ServiceDown` answers 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 list `PICKS`, and `reset_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.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 comments at the top of `routers/tonight.py` and `routers/picks.py` list every request the API should answer:

```text
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": "..."}`.

1. **Give the client a timeout.** In `services.py`, make `make_client` give its `httpx.AsyncClient` a timeout of 2 seconds, keeping the `transport` it's handed.
2. **Ask one service.** In `routers/tonight.py`, write a helper `async 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, raise `ServiceDown(service)` instead.
3. **Ask both at once.** Write `GET /tonight` as an `async def` route that takes `client: Annotated[httpx.AsyncClient, Depends(get_client)]` and awaits `ask` for both services together with `asyncio.gather`.
4. **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 with `HTTPException` when there's none.
5. **Save the pick, then tell the chat.** In `routers/picks.py`, write `POST /picks`: answer 201 with the new pick, and add `post_to_group_chat` as a background task with the pick.

## Check your work

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

```bash
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 `try` inside `ask`, around `await client.get(url)` and `response.raise_for_status()`, with `except httpx.HTTPError`. A `try` around the whole `asyncio.gather` can't tell the two services apart.
- **`asyncio.gather` gives 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)`; with `post_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:

```json
{"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:

```text
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:

```json
{"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.

1. 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.
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:

   ```bash
   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 main
   ```

3. Paste 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.

## Key terms

- [async def](https://www.ask-codey.com/glossary/async-def)
- [httpx](https://www.ask-codey.com/glossary/httpx)
- [Timeout](https://www.ask-codey.com/glossary/timeout-rest-api)
- [503 Service Unavailable](https://www.ask-codey.com/glossary/503-service-unavailable)
- [Background Tasks](https://www.ask-codey.com/glossary/background-tasks)

## Related

- [async and await in Plain Words](https://www.ask-codey.com/lessons/fastapi-async-await-plain-words)
- [Async Routes: When They Help, and When They Don't](https://www.ask-codey.com/lessons/fastapi-async-routes-when-they-help)
- [Work That Runs After the Response](https://www.ask-codey.com/lessons/fastapi-background-tasks)

Source: https://www.ask-codey.com/lessons/exercise-fastapi-movie-night-picker
