Exercise: Team Task Board
Finish Crew Board's FastAPI task board with a get_current_user dependency, a require_role dependency and an ownership check, so anyone signed in reads the board and adds tasks, members change only their own tasks and only an admin deletes, and let the tests check every rule as each kind of user.
Journeyman · FastAPI · REST API · Updated
Crew Board's team has a task board API with a working sign-in, and nothing else checks who's asking: anyone can read, add, change or delete any task. You'll add the rules the team agreed on. Anyone signed in reads the board and adds tasks, members change only their own tasks, and only an admin deletes. The sign-in route is ready, so the work is all authorization: two dependencies, an ownership check and the task routes that use them. Tests sign in as each kind of user and check every rule as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-team-task-board, 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-team-task-board.git
Git makes a folder, exercise-fastapi-team-task-board, 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 app signs its tokens with a secret from the environment variable JWT_SECRET, so set a practice one in the same terminal before you start the app (the tests set their own). On Windows, $env:JWT_SECRET = "change-me-practice-secret-for-crew-board"; on a Mac, export JWT_SECRET="change-me-practice-secret-for-crew-board".
The folder holds:
dependencies.py: the dependencies, for you to write. Its top comment says what each one does and answers.routers/tasks.py: the task routes, for you to finish. They work, but none of them checks who is asking.security.py: the sign-in helpers, withSECRET_KEYandALGORITHMfor checking a token. A token's payload holds the user's id, as text, in"sub". Ready to use.routers/auth.py: the sign-in route,POST /auth/token, which takes the docs page's sign-in form. Ready to use.crew_data.py,database.pyandmigrations/: the data module with every SQL statement,get_db, and the tables with the practice team and their four tasks. Ready to use.errors.pyandmain.py: the one error shape, and the app that puts it all together. Ready to use.tests/test_tasks.py: the tests, which sign in as each of the team on a throwaway database. You don't need to change it.
The practice team signs in with these emails and passwords:
| Name | Password | Role | Owns | |
|---|---|---|---|---|
| Maya | maya@example.com |
practice-maya |
admin | task 1 |
| Theo | theo@example.com |
practice-theo |
member | tasks 2 and 4 |
| Sofia | sofia@example.com |
practice-sofia |
member | task 3 |
What to do
The comment at the top of routers/tasks.py lists every request, who may send it and what it answers:
Every request needs a signed-in user: its token in the Authorization: Bearer header.
With no token: 401, detail "Not authenticated" (oauth2_scheme answers it)
With a made-up or expired one: 401, detail "Your token isn't valid. Sign in again."
Both with the header WWW-Authenticate: Bearer.
GET /tasks Anyone signed in. 200, every task, in id order.
GET /tasks/2 Anyone signed in. 200, task 2. 404 when there's no such task.
POST /tasks Anyone signed in. Body {"title": "Plan the team retro"}. 201, the new task,
owned by whoever is signed in: {"id": 5, "title": "Plan the team retro",
"owner_id": 2, "done": false} for Theo. An owner_id in the body changes nothing.
PATCH /tasks/2 The task's owner, or an admin. Body {"done": true}: 200, the changed task.
403 for anyone else: detail "Only the task's owner or an admin may change it."
404 when there's no such task, before the owner is checked.
DELETE /tasks/3 Admins only. 204, no body.
403 for a member: detail "You need the admin role for that." (whether the task
is there or not). 404 for an admin when there's no such task.
- Read the token. In
dependencies.py, makeoauth2_schemewithOAuth2PasswordBearer, whosetokenUrlis the sign-in route,auth/token. - Load the signed-in user. Write
get_current_user: decode the token, load the user whose id is in"sub", and refuse a made-up or expired token, or a user who isn't there, with the 401 above. Then make theCurrentUsertype hint. - Require a signed-in user on every task route, and save a new task with the signed-in user as its owner, never an
owner_idfrom the body. - Check ownership in the PATCH route, after the 404, letting an admin through.
- Require the admin role to delete. Write
require_role(role), a function that makes a dependency, and putrequire_role("admin")on the delete route's decorator.
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, and every test gets a fresh database. At first 8 of the 20 tests pass: the requests a signed-in user is allowed to make work already, since the routes don't check anything yet. The other 12 fail, and each one's message says what it sent, what it expected and what came back, for example GET /tasks with no token should answer 401, but it answered 200 with [...]. Each step you finish turns its tests green.
To try the API yourself, start it with fastapi dev main.py and open http://127.0.0.1:8000/docs. Click Authorize and sign in as one of the team, then send requests with Try it out. To switch users, click Authorize, then Logout, and sign in again. Stop the server with Ctrl+C.
Hints
- Start with
get_current_user. Requiring a Signed-In User writes one:Depends(oauth2_scheme)gives it the token,Depends(get_db, scope="function")the connection,jwt.decodewithSECRET_KEYandalgorithms=[ALGORITHM]checks the token, andexcept jwt.InvalidTokenErrorcatches every token it can't check, an expired one included. - The 401 needs its header. Pass
headers={"WWW-Authenticate": "Bearer"}to theHTTPException;errors.pysends it on. user: CurrentUseron a route is all it takes to require a signed-in user. Tests 1 to 4 turn green onceGET /taskshas it.- A new task's owner is
user["id"]. Takeowner_idout ofTaskIn; a field the model doesn't have is ignored. require_rolereturns a function,check_role(user: CurrentUser), which raises the 403 or returns the user. Roles and Ownership: 401 or 403 shows it, and why a member'sDELETE /tasks/99is a 403, not a 404.
When you're done
Every test is green: pytest's last line says 20 passed. And on the docs page, signed in as Theo, DELETE /tasks/{task_id} for task 3 answers 403 with:
{"status":403,"title":"Forbidden","detail":"You need the admin role for that."}
Then sign in as Maya and send it again: 204, and Sofia's task is gone.
Now look back at your dependencies. If the team added a third role, lead, who may delete tasks too, what would change in require_role, and what would change in the delete route?
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-team-task-board), 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-team-task-board.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-team-task-board, 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
A signed-in user from one dependency, a role check made by a function, and an ownership check that trusts only the token are how nearly every API with accounts decides who may do what, and your tests now prove each rule for each kind of user.