Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 50 ยท Structuring larger apps

Routers and project layout

Split a growing FastAPI app with APIRouter: prefixes, tags, include_router, and a layered layout of routers, services and schemas, shown in a runnable single file.

A tutorial app fits in one file. A real API does not: after a few dozen endpoints, a single main.py becomes a wall of code where users, orders and billing are tangled together, and two developers keep editing the same lines. FastAPI's answer is the APIRouter: a mini application that holds a group of related endpoints and is plugged into the main app later.

This lesson shows how to group endpoints with routers, give them URL prefixes and documentation tags, and arrange a project in layers so that each file has one job. Because the in-browser runner executes one file at a time, the examples mark each "module" with a comment such as # ---- routers/books.py ----; on your own machine each comment becomes a real file.

APIRouter in one minute

An APIRouter has the same decorators as FastAPI (@router.get, @router.post and so on). You create it in one module, define endpoints on it, and in main.py call app.include_router(router). Three settings make routers pleasant:

  • prefix: a path added before every route, so you write "/{book_id}" instead of "/books/{book_id}".
  • tags: labels that group the endpoints in the generated documentation.
  • dependencies: shared dependencies, as in Router-level and global dependencies.

You may also pass prefix, tags and dependencies to include_router itself. The prefixes add up: a router with prefix="/books" included with prefix="/v1" serves /v1/books. That is the usual way to version an API without touching the routers.

A layered layout

Routers answer "which URLs exist?". They should not also contain the business rules and the data access. Most teams separate three concerns:

Three layers, three jobs

Routers HTTP only. Parse input, call a service, return output.
Services Business rules in plain Python, no FastAPI imports.
Schemas Pydantic models that describe the data going in and out.

Dependencies connect the layers, for example by providing a database session.

1 / 2

A common folder structure looks like this (read-only; the folder names are conventions, not requirements):

TEXT
app/
โ”œโ”€โ”€ main.py            # creates FastAPI(), includes routers, adds middleware
โ”œโ”€โ”€ config.py          # settings (see the next lesson)
โ”œโ”€โ”€ dependencies.py    # get_current_user, get_session, ...
โ”œโ”€โ”€ schemas/           # Pydantic models: BookIn, Book, ...
โ”‚   โ””โ”€โ”€ books.py
โ”œโ”€โ”€ services/          # business rules, plain Python
โ”‚   โ””โ”€โ”€ books.py
โ””โ”€โ”€ routers/           # APIRouter objects, one per resource
    โ”œโ”€โ”€ books.py
    โ””โ”€โ”€ authors.py
tests/
โ””โ”€โ”€ test_books.py

The arrows between layers point one way: main imports routers, routers import services and schemas, services import schemas and your database code. A service must never import a router. If you notice a circular import, a piece of code is probably living in the wrong layer.

Everything in one runnable file

The following example plays all roles in one file. Look for the four section comments; imagine each as its own module. The service raises a plain LookupError, knowing nothing about HTTP. The router translates it into an HTTPException with a status code. That translation is the router's job, and it keeps the service reusable outside a web request.

Python Routers, services and schemas in one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the output:

  • Creating a book for author 2 returns the stored book; author 9 fails with a 422 and the message the service produced.
  • GET /v1/books/1 works, but plain /books/1 is 404, because the prefix /v1 was added at include time.
  • The last three lines are read from /openapi.json. Each route carries its router's tag, and the full path shows both prefixes joined. In the interactive docs the tags become collapsible groups.

Empty string paths are legal in a router: @books_router.post("") combines with the prefix into exactly /v1/books. (A path that is just "/" would produce /v1/books/, with a trailing slash.)

Prefixes and tags at include time

Because a router is just an object, you can even build routers with a function and mount the same code several times. The next example creates a router per resource, then includes users twice: as /v1 and as /v2 with an extra beta tag. The loop prints the routes FastAPI registered, so you can see exactly how prefixes and tags combine.

Python Mounting routers with prefixes and extra tags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The /v2/users routes carry both tags, with the include-time tag listed first. The same function bodies serve two versions, which is handy while you migrate clients, though a real v2 usually gets its own router module.

Practical advice

  • One router per resource (users, orders, invoices). If a router grows past a few hundred lines, split it by sub-resource.
  • Keep main.py boring: create the app, add middleware, include routers, nothing else. Business logic in main.py is a smell.
  • Put shared dependencies in one module (dependencies.py) so routers can import them without importing each other.
  • Prefer explicit imports over from x import *, and import services inside routers, not the other way around, to avoid circular imports.
  • Version at the include step: include_router(router, prefix="/v1") makes a later /v2 easy to add side by side.
  • Name operations sensibly: function names become operation ids in the docs, so create_book beats post1.

Group by feature instead of by layer when the app grows large: a books/ package containing router.py, service.py and schemas.py. Both layouts work. Choose one and keep it consistent across the project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A router is created with prefix="/books" and included with app.include_router(router, prefix="/v1"). Its route @router.get("/{book_id}") is served at which path?

    Prefixes are concatenated from the outside in: the include prefix first, then the router's own prefix, then the route path.
  2. 2. What is the main job of a router function in a layered layout?

    Routers are the HTTP layer. Rules belong in services and data shapes in schemas, so the rules can be reused and tested without a web request.
  3. 3. What do tags=["books"] on a router change?

    Tags are documentation metadata. They do not affect routing or behavior.
  4. 4. Why should a service raise LookupError rather than HTTPException?

    Translating domain errors into status codes is the router's job. A service that knows nothing about HTTP can be called from scripts and tests as well.

Summary

  • APIRouter groups related endpoints; app.include_router(router) plugs it into the app.
  • prefix, tags and dependencies can be set on the router or at include time; prefixes add up.
  • Separate layers: routers (HTTP), services (rules), schemas (data shapes); imports flow one way.
  • Keep main.py small and put shared dependencies in their own module.
  • On this site the "modules" live in one file with comments; the structure is identical on disk.

Next: Settings and configuration shows how to keep secrets and per-environment values out of your code.