# Exercise: Harden the Coffee Club API

Harden Bean There Coffee Club's working FastAPI app before it goes online, with CORS for the club's two web pages, security headers from a middleware, a slowapi rate limit on sign-in, an update model that can't set role, and the JWT secret read from the environment, and let the tests check every job.

Journeyman · FastAPI · Web Development · Updated November 19, 2026

By Gregor Dzierzon

Bean There Coffee Club's API works: members sign in, read their own record and change their favorite roast, and staff can list every member. Next week it goes online, where anyone can send it anything. You'll harden it the way this chapter did, one job at a time: CORS for the club's own web pages, security headers on every answer, a rate limit on sign-in, an update model that can't make anyone staff, and the secret that signs tokens moved out of the code. Tests check every job as you go.

## Get the exercise code

Open this lesson's GitHub repository, [github.com/ask-codey/exercise-fastapi-harden-the-coffee-club-api](https://github.com/ask-codey/exercise-fastapi-harden-the-coffee-club-api), 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-harden-the-coffee-club-api.git
```

Git makes a folder, `exercise-fastapi-harden-the-coffee-club-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):

```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.

Then make your own `.env`, as *Keeping Secrets Out of Your Code* does: copy `.env.example` to `.env` (`Copy-Item .env.example .env` in PowerShell, `cp .env.example .env` in zsh), and replace `change-me` with a real secret from `python -c "import secrets; print(secrets.token_urlsafe(32))"`. The tests don't need it, but `fastapi dev` will once job 5 is done.

The folder holds:

- `main.py`: the app, its routers and its error handlers. Jobs 1, 2 and 3 go here, and the comment at its top lists every route and every job.
- `rate_limit.py`: where the limiter goes (job 3).
- `routers/auth.py`, `routers/members.py` and `routers/roasts.py`: the routes, all working. The sign-in route gets its limit in job 3.
- `models.py`: `MemberChanges`, the body of `PATCH /members/me` (job 4).
- `auth.py`: passwords with pwdlib, tokens with PyJWT, and the signed-in member. Job 5 goes here.
- `database.py`, `club_data.py` and `migrations/`: the SQLite database, every SQL statement and the tables, ready to use. The app adds three roasts and two members the first time it starts: Dana (`dana@example.com`, password `correct-horse-staple`) and Marcus, who is staff (`marcus@example.com`, password `latte-art-staple`).
- `tests/`: the tests, which send requests to your app with `TestClient` on a throwaway database. You don't need to change them.
- `requirements.txt`, `pytest.ini`, `.env.example` and `.gitignore`: the packages at exact versions, where pytest finds things, the settings the API needs, and the files Git leaves out (`.env` among them).

## What to do

Every route already answers. The comment at the top of `main.py` lists the five jobs:

```text
1. CORS: only the club's web pages, https://www.beanthere.example and https://beanthere.example, may call the API
   from a browser, with GET, POST and PATCH, and the Authorization and Content-Type headers. A page from any other
   origin gets no Access-Control-Allow-Origin header.
2. Security headers: every answer carries X-Content-Type-Options: nosniff, X-Frame-Options: DENY and
   Referrer-Policy: no-referrer.
3. A rate limit on POST /auth/token only: 5 tries a minute from one address. The sixth answers 429 in the one error
   shape, detail "Too many sign-in tries. Try again in a minute.", with the header Retry-After: 60.
4. (models.py) PATCH /members/me may change only name and favorite_roast. A body with any other field, such as role
   or email, answers 422.
5. (auth.py) JWT_SECRET comes from the environment, and the app stops with a clear message when it isn't set.
```

1. **Add CORS** with `CORSMiddleware` and an allow-list of the club's two origins.
2. **Add a middleware** that puts the three security headers on every answer.
3. **Limit sign-in:** make `limiter` in `rate_limit.py`, put it on `app.state`, add a handler for `RateLimitExceeded` that answers with `problem()`, and put the limit on the sign-in route.
4. **Fix `MemberChanges`:** only `name` and `favorite_roast`, and extra fields forbidden.
5. **Write `read_secret(name)`** in `auth.py`, as its docstring says, and set `JWT_SECRET = read_secret("JWT_SECRET")`.

Keep every route answering as it does now: the tests sign Dana in and change her record along the way.

## Check your work

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

```bash
pytest
```

No server needs to be running, and your `coffee_club.db` and `.env` are never touched: each test makes a new database, and the tests bring their own secret. At first 11 of the 15 tests fail, and 4 pass: those check what already works, such as Dana signing in, and that no other site gets a CORS header. Each job you finish turns its tests green. A failing test's message says what came back, for example *PATCH /members/me with {"favorite_roast": "Midnight Harbor", "role": "staff"} should answer 422, but it answered 200 with {..."role":"staff"}*.

To try the API yourself, start it with `fastapi dev main.py` and open `http://127.0.0.1:8000/docs`. Click **Authorize**, sign in as Dana, and try **PATCH /members/me**. Stop the server with **Ctrl+C**.

## Hints

- **CORS:** *CORS: Which Web Pages May Call Your API* adds `CORSMiddleware` with `app.add_middleware`. An origin matches exactly, so `https://beanthere.example` and `https://www.beanthere.example` are both on the list.
- **Headers:** *Rate Limits and Security Headers* writes the middleware with `@app.middleware("http")`, `async def` and `await call_next(request)`.
- **The limit:** the same lesson makes `Limiter(key_func=get_remote_address)`, sets `app.state.limiter`, and handles `RateLimitExceeded`. `@limiter.limit("5/minute")` goes under `@router.post("/token")`, and the route needs a `request: Request` parameter, or the app won't start.
- **The model:** *The Attacks to Expect: Injection and Mass Assignment* takes `role` out and adds `model_config = ConfigDict(extra="forbid")`. The one error shape's 422 handler names each extra field for you.
- **The secret:** *Keeping Secrets Out of Your Code* reads it with `os.environ.get` and raises `RuntimeError` when it's missing or empty. `load_dotenv()` is already called at the top of `auth.py`.

## When you're done

Every test is green: pytest's last line says `15 passed`. Then, with the server running, open the docs page, sign in as Dana and send **PATCH /members/me** with `{"role": "staff"}`: it answers 422, and **GET /members** still answers 403 for her. Rename your `.env` for a moment and start the app: it stops at once, with your sentence on the last line.

Now look back at the jobs. Which of them would still protect the club if someone called the API from a script instead of a browser, and which wouldn't?

## 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. Your `.env` stays behind, because `.gitignore` lists it.

1. On GitHub, click **+**, then **New repository**. Name it (for example `exercise-fastapi-harden-the-coffee-club-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:

   ```bash
   git remote set-url origin https://github.com/your-name/exercise-fastapi-harden-the-coffee-club-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-harden-the-coffee-club-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

CORS, security headers, a rate limit, an allow-list of fields and secrets kept out of the code are the checklist every API goes through before it faces the internet, and you've now worked through all of it on a real app with tests that prove each one.

## Key terms

- [CORS Middleware](https://www.ask-codey.com/glossary/cors-middleware)
- [slowapi](https://www.ask-codey.com/glossary/slowapi)
- [Security Headers](https://www.ask-codey.com/glossary/security-headers)
- [Mass Assignment](https://www.ask-codey.com/glossary/mass-assignment)
- [Environment Variable](https://www.ask-codey.com/glossary/environment-variable)

## Related

- [CORS: Which Web Pages May Call Your API](https://www.ask-codey.com/lessons/fastapi-security-cors)
- [Rate Limits and Security Headers](https://www.ask-codey.com/lessons/fastapi-security-rate-limits-and-headers)
- [Keeping Secrets Out of Your Code](https://www.ask-codey.com/lessons/fastapi-security-secrets)
- [The Attacks to Expect: Injection and Mass Assignment](https://www.ask-codey.com/lessons/fastapi-security-common-attacks)

Source: https://www.ask-codey.com/lessons/exercise-fastapi-harden-the-coffee-club-api
