Organizing Routes with APIRouter
APIRouter moves each resource's routes into its own file in a routers package, with a prefix that starts every path and a tag that groups them on the docs page, and app.include_router wires each one in, so main.py only puts the app together.
Journeyman · FastAPI · REST API · Updated
After this lesson you can
- Move a resource's routes into their own file with APIRouter, a prefix and tags, and add them to the app with app.include_router
- Work out the full address of a router's route from its prefix and path, and keep main.py to putting the app together
Key takeaways
- An APIRouter holds a group of routes, written with @router.get and @router.post instead of @app.get and @app.post.
- The router's prefix is put in front of every path in it. With prefix="/games", the route "/{game_id}" answers at /games/{game_id}, and the empty path "" answers at /games itself.
- The router's tags group its routes under one heading on the docs page.
- app.include_router adds a router's routes to the app. Until it runs, none of them answers.
- With one file per resource in a routers folder, main.py only makes the app and includes the routers.
A real API has more than one kind of thing in it: a shop has products, orders and customers; a school has students, classes and grades. Put every route for all of them in one file, and it grows into hundreds of lines where two people changing different things edit the same file. This lesson splits an API into one file per resource, the way FastAPI projects you'll meet at work are laid out.
The example is the Rolling Dice café, whose API now looks after its tables as well as its games.
One file gets crowded
The café's main.py has the games routes from this chapter: the list with its filters, one game, adding a game and recording a play. Now staff want to see the tables too: GET /tables and GET /tables/{table_id}. Added to main.py, they sit between the games routes and the games data, and the file reaches about a hundred lines. Every new resource (events, snack orders) makes it longer, and finding the route you want means scrolling past all the others.
The fix is the one you'd use for a messy desk drawer: a separate box for each kind of thing.
A router: one file per resource
An APIRouter is a box of routes. It works like the app for writing routes, with @router.get instead of @app.get, but it isn't an app; it's added to one later. Make a folder named routers beside main.py, with an empty file named __init__.py inside it (read "dunder init", for the double underscores). That file makes the folder a package: a folder of Python files that import can reach into. Then the games get their own file, routers/games.py:
from fastapi import APIRouter, HTTPException
router = APIRouter(prefix="/games", tags=["games"])
GAMES = [
{"id": 1, "title": "Harbor Lights", "min_players": 2, "max_players": 4, "minutes": 45, "available": True},
{"id": 2, "title": "Moon Mice", "min_players": 3, "max_players": 6, "minutes": 20, "available": False},
{"id": 3, "title": "Tile Town", "min_players": 1, "max_players": 2, "minutes": 30, "available": True},
]
@router.get("")
def list_games():
return GAMES
@router.get("/{game_id}")
def get_game(game_id: int):
for game in GAMES:
if game["id"] == game_id:
return game
raise HTTPException(status_code=404, detail=f"There's no game {game_id}.")
The prefix is put in front of every path in the router, so a route's own path says only what comes after /games. "/{game_id}" answers at /games/{game_id}. The empty path "" answers at the prefix itself, /games.
Watch for "/" instead of "". With the prefix, it makes the address /games/ (with a slash at the end), and a request for /games gets a 307 Temporary Redirect, an answer that says "ask at /games/ instead". Browsers follow it without a word, but it's an extra round trip, and some apps don't follow it. "" keeps the address exactly /games.
The tags label the router's routes; the docs page uses them as headings. routers/tables.py is built the same way, with prefix="/tables", tags=["tables"] and its own TABLES list.
main.py puts the app together
A router's routes answer nothing until the app includes it. main.py now has one job, putting the app together:
from fastapi import FastAPI
from routers import games, tables
app = FastAPI(title="Rolling Dice")
app.include_router(games.router)
app.include_router(tables.router)
from routers import games, tables brings in the two files from the routers package, and games.router is the router made in routers/games.py. app.include_router adds each router's routes to the app, prefixes and all. title="Rolling Dice" names the API at the top of the docs page.
Run it with fastapi dev main.py as before. The project now looks like this:
rolling-dice/
├── main.py
└── routers/
├── __init__.py
├── games.py
└── tables.py
/games/2 still answers with Moon Mice, /tables with the café's tables, and /tables/9 with a 404 whose body is {"detail":"There's no table 9."}. Nothing a request sees has changed; only where the code lives.
The docs page, grouped by tag
Open /docs: each tag is now a heading, with its routes under it, so a developer who wants the tables finds them in one place.
When the café adds snack orders, that's one new file, routers/snacks.py, and one new line in main.py. Nobody working on the games has to touch it.
Check yourself
2 questions to try on the lesson page.
So what
One file per resource keeps every route quick to find as an API grows, and a main.py that only includes routers shows the whole API at a glance.