Exercise: Shuttle Schedule API
Get a campus shuttle's FastAPI app ready for real riders, with pydantic-settings that stop it at startup naming every missing setting, a request line for every request, a logging filter that hides passwords and tokens, a lifespan that runs the migrations, and a /health route that answers 200 or 503.
Journeyman · FastAPI · REST API · Updated
The Campus Shuttle API already tells riders where every route goes, and drivers can sign in. Before the college puts it in front of real riders, the team wants five things: settings that stop the app when one is missing, a log line for every request, no password or token in any log line, migrations that run as the app starts, and a health check the host can call. You'll build all five, and tests check each one as you go.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-shuttle-schedule-api, 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-shuttle-schedule-api.git
Git makes a folder, exercise-fastapi-shuttle-schedule-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, then copy .env.example to .env. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
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. .env is in .gitignore, so your own values never reach GitHub.
The folder holds:
settings.py: theSettingsclass andload_settings(), for you to finish. Right now every setting has a default, the JWT secret included, and.envisn't read.logs.py: theHideSecretsfilter, for you to finish, andsetup_logging(level), which puts it on the handler that writes every line. Ready.main.py: the app, its routers and the error handlers, ready. The lifespan, the request-logging middleware andGET /healthare yours to write.database.py:open_db,migrateandget_db, which openssettings.database_pathfor every request. Ready.migrations/,shuttle_data.pyandrouters/: the routes, their stops and the drivers' sign-in. Ready.tests/test_shuttle.py: 19 tests, which set their own settings and use a throwaway database file. You don't need to change it.requirements.txt,pytest.iniand.env.example: the pinned packages, where pytest finds the tests, and the four settings with made-up values.
What to do
The comment at the top of each file you finish says exactly what it must do. In short:
settings.py DATABASE_PATH and JWT_SECRET required; LOG_LEVEL "INFO" and TOKEN_MINUTES 60 by default; read .env too.
load_settings() stops the app, one line per problem:
The shuttle API can't start. Fix these settings in the environment or in .env:
JWT_SECRET: Field required
logs.py password=correct-horse-staple -> password=***
token=abc123 -> token=***
Bearer abc.def.ghi -> Bearer ***
main.py at startup: Shuttle API started: ran migrations [1, 2, 3]
at shutdown: Shuttle API stopped
every request: GET /routes 200 3.1ms (the path without its query string)
GET /health 200 {"status": "ok"}, or 503 {"status": 503, "title": "Service Unavailable",
"detail": "The database isn't answering."} and an ERROR line: Health check failed: ...
- Settings that stop the app. In
settings.py, take the defaults offdatabase_pathandjwt_secret, read.envwithSettingsConfigDict, and catch theValidationErrorinload_settings, stopping withsys.exitand the message. - Hide the secrets. In
logs.py, writeHideSecrets.filter:password=andtoken=words, as in the Do It in Logging an API, and the word right afterBearer. - A line for every request. In
main.py, a middleware that logs the method,request.url.path, the status code and the time, withmain.py's own logger. - Migrations at startup. A lifespan that opens
settings.database_path, runsmigrate, closes it and logs the startup line, then the shutdown line afteryield; thenFastAPI(title="Campus Shuttle", lifespan=lifespan). - A health check.
GET /health, withDepends(get_db, scope="function"), that counts theroutestable's rows and answers 200, or 503 throughproblem()with the ERROR line.
Check your work
Run the tests from the exercise folder, with the virtual environment on:
pytest
No server needs to be running, and your own .env and shuttle.db aren't touched. At first all 19 tests fail. That's expected: tests 1 to 6 turn green as settings.py is done, 7 to 9 with the filter, 10 to 13 with the middleware, 14 to 17 with the lifespan, and 18 and 19 with the health route. A failing test's message says what it expected and what came back, for example Settings() with no JWT_SECRET anywhere should be refused, but it was made: give jwt_secret no default.
Then run the app with fastapi dev main.py and open http://127.0.0.1:8000/docs. Watch the terminal as you try each route: the startup line, one line per request, and the shutdown line when you press Ctrl+C.
Hints
- Start with
settings.py, the way Settings Checked at Startup writes it.str(problem["loc"][0]).upper()turnsjwt_secretintoJWT_SECRET, and each line starts with two spaces. - For
Bearer, keep a variable that remembers whether the last word wasBearer; when it was, the word you're on becomes***. - The middleware and the lifespan are
async def, withawait call_next(request), as Logging an API and Startup, Shutdown and a Health Check show. Log withlogger, already made at the top ofmain.py. migrate(conn)returns the numbers it ran, sologger.info("Shuttle API started: ran migrations %s", ran)writes[1, 2, 3]on a new database and[]the next time.- The health route catches
sqlite3.Error, logs it withlogger.error, and sends only the calm sentence throughproblem(503, ...).
When you're done
Every test is green: pytest's last line says 19 passed. Rename .env to env.txt and run fastapi dev main.py again. The app stops before it serves anything:
The shuttle API can't start. Fix these settings in the environment or in .env:
DATABASE_PATH: Field required
JWT_SECRET: Field required
Rename it back, and it starts. Now think about the host: when it starts this API with a setting missing, how long does it take for someone to find out, compared with an API that reads os.environ inside the sign-in 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-shuttle-schedule-api), 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-shuttle-schedule-api.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-shuttle-schedule-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.
.env stays on your computer: .gitignore leaves it out of git add .. Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
An API that refuses to start with a bad setting, writes one honest line per request with nothing secret in it, migrates itself and answers a health check is an API a host can run without you watching, which is what "ready for real users" means.