APIs with FastAPI · Chapter 8 of 26
Routers and structure
By the end of this chapter you can split an API into routers with their own prefixes and tags, lay a project out in files and packages, read settings from the environment with types, load data once when the app starts with a lifespan, and say why settings are read once and handed out as a dependency. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Structure and data
- 4 tasks
- FastAPI
- In the all labs plan
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.
Why you need this
DakiyaGo's API is one file of 600 lines now. Aman, Imran and a new engineer all edit it, and every pull request touches the same file. The rate card's path, the page size and the cash-on-delivery switch are written into the code, so the copy on Aman's laptop and the copy in production cannot differ without someone editing code before a deploy. And the data is read at the top of the file, so every test, every tool that imports the file, pays for reading it.
None of this is a FastAPI feature you have missed; it is how the API is arranged. Real APIs keep routes in several files, take their settings from the environment they run in, and do their startup work in one known place, with a matching place for shutdown.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
main.py: two routers, one app
DakiyaGo's API is outgrowing one file. Split it into three files in this folder. parcels_routes.py has an APIRouter in a variable called router with GET /parcels (every parcel in /workspace/data/parcels.json, in the file's order) and GET /parcels/{awb} (that parcel, or 404). pincodes_routes.py has a router with GET /pincodes/{pincode} (that pincode's entry from pincodes.json, or 404).
main.py makes the app, includes both routers, and keeps one route of its own: GET /health answering {"status": "ok"}. In /openapi.json the parcels routes have the one tag parcels, and the pincode route the one tag pincodes. The routes are written in their router's file; main.py only includes them.
- Task 2
settings.py: settings from the environment
The same code will run on Aman's laptop, in staging and in production, with different settings. In settings.py, write a class Settings from pydantic-settings' BaseSettings that reads environment variables starting with DAKIYAGO_: app_name (text, default DakiyaGo API), max_page_size (a whole number, default 50) and cod_enabled (true or false, default true).
Make the settings once, at the top of the file. The app's title is app_name, and GET /config answers an object with exactly those three keys and their values, typed (with DAKIYAGO_MAX_PAGE_SIZE=20 it answers the number 20; with DAKIYAGO_COD_ENABLED=false, false). A wrong value, like DAKIYAGO_MAX_PAGE_SIZE=fifty, stops the app when the file is imported.
- Task 3
lifespan.py: load the data when the app starts
Make an app with a lifespan: when the app starts, it reads /workspace/data/rate_card.json and pincodes.json once and keeps them (on app.state, or anywhere the routes can see). Importing the file reads nothing.
GET /delivery/{pincode} answers an object with exactly pincode, city and zone (from pincodes.json) and days (that zone's days from the rate card, as the card has it), or 404 for a pincode the file does not have. The check imports your file with data reads switched off, starts the app, and switches them off again for the requests.
- Task 4 · interview question
Interview: cached_settings.py, read the settings once
Write a Settings class (pydantic-settings, prefix DAKIYAGO_) with one field, max_page_size (a whole number, default 50), and a function get_settings that returns the settings, made once and then kept. GET /parcels?limit= (default 10) takes its settings from get_settings as a dependency: a limit above max_page_size answers 422; otherwise it answers {"max_page_size": ..., "items": [...]}, the first limit parcels from parcels.json.
The check sets DAKIYAGO_MAX_PAGE_SIZE, then changes it while the app runs (the app must keep its first value), then overrides get_settings with Settings(max_page_size=5), as a test would. The interviewer will ask: why not read the environment inside every route?
What you will learn
- APIRouter: routes in their own file, with a prefix and tags.
- A project laid out in files, and how the lab's folder holds one.
- Settings from the environment with pydantic-settings: typed, checked at startup.
- Lifespan: work at startup, cleanup at shutdown.
- Settings once, as a dependency a test can replace.
More in Structure and data
Build "Routers and structure" yourself
DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.