Skip to content

05 · APIRouter and a Multi-File Application

So far, our application has lived in one Python file.

That helped us see the complete request lifecycle without jumping between modules. But as an application grows, one file quickly becomes a mixture of unrelated concerns:

Login routes
Document routes
User routes
Admin routes
Database setup
Security functions
Services
Middleware
Configuration

Today we’ll separate the document routes into their own module using APIRouter.

The important point is that this changes how the code is organized, but not the fundamental request lifecycle.

The browser still communicates with one FastAPI application:

Browser → middleware → main application → matching route → authorization → response

APIRouter helps assemble that application during startup.

It does not create another server or an extra network request.


Our small application will now look like this:

app/
├── __init__.py
├── main.py
├── data.py
├── security.py
└── routers/
├── __init__.py
└── documents.py

Each file has one general responsibility:

File Responsibility
main.py Creates and assembles the FastAPI application
data.py Holds our temporary user and document data
security.py Contains authentication and authorization helpers
routers/documents.py Defines document-related HTTP routes

The __init__.py files tell Python that these directories should be treated as packages.

They can be empty.

FastAPI’s official documentation recommends APIRouter for organizing larger applications across multiple files. If you know Flask, the closest equivalent is a Blueprint. (FastAPI documentation)


We’ll move our temporary dictionaries into their own module:

users_by_id = {
1: {
"id": 1,
"username": "max",
"firm_id": 10,
"role": "member",
},
2: {
"id": 2,
"username": "sara",
"firm_id": 20,
"role": "member",
},
99: {
"id": 99,
"username": "admin",
"firm_id": None,
"role": "admin",
},
}
documents_by_id = {
101: {
"id": 101,
"firm_id": 10,
"title": "Northstar Studio Website Review",
},
202: {
"id": 202,
"firm_id": 20,
"title": "Harbor Studio Document Review",
},
}

This file does not know anything about FastAPI.

It does not contain:

  • Routes
  • Requests
  • Responses
  • Cookies
  • Status codes

It merely creates two Python dictionaries.

When we later introduce SQLAlchemy, data.py will disappear or change substantially. SQLite will become the data source.

For now, separating the dictionaries keeps the router focused on HTTP behavior.


Our authentication and authorization helpers move here:

from fastapi import Request
from .data import users_by_id
def get_authenticated_user(request: Request):
user_id = request.session.get("user_id")
if user_id is None:
return None
return users_by_id.get(user_id)
def user_can_view_document(
user: dict,
document: dict,
) -> bool:
if user["role"] == "admin":
return True
return user["firm_id"] == document["firm_id"]

The import:

from .data import users_by_id

starts with one dot.

That dot means:

Start from the current Python package, app.

The complete import target is conceptually:

app.data.users_by_id

security.py needs the user dictionary because authentication retrieves the authoritative user record after reading the user ID from the session.

The functions themselves remain the same:

get_authenticated_user(request)

answers:

Who is making this request?

And:

user_can_view_document(user, document)

answers:

May this user view this document?


Now we create the document router:

from html import escape
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from ..data import documents_by_id
from ..security import (
get_authenticated_user,
user_can_view_document,
)
router = APIRouter(
prefix="/documents",
tags=["documents"],
)
@router.get(
"/{document_id}",
response_class=HTMLResponse,
)
async def document_page(
request: Request,
document_id: int,
):
user = get_authenticated_user(request)
if user is None:
return RedirectResponse(
url="/login",
status_code=303,
)
document = documents_by_id.get(document_id)
if document is None:
raise HTTPException(
status_code=404,
detail="Document not found",
)
if not user_can_view_document(user, document):
raise HTTPException(
status_code=404,
detail="Document not found",
)
return f"""
<html>
<body>
<h1>{escape(document["title"])}</h1>
<p>Document ID: {document["id"]}</p>
<p>Firm ID: {document["firm_id"]}</p>
<p>Viewed by: {escape(user["username"])}</p>
</body>
</html>
"""

This looks almost identical to the route from the previous tutorial.

The major change is here:

router = APIRouter(
prefix="/documents",
tags=["documents"],
)

And here:

@router.get("/{document_id}")

Previously we registered the route directly on:

app

Now we register it on:

router

router = APIRouter(
prefix="/documents",
tags=["documents"],
)

APIRouter is a Python class.

Calling it creates an object:

router

That object can collect related path operations.

You can think of it as a smaller route registry that will later be attached to the main application.

It is not a complete standalone web server.

It does not listen on a port.

It does not receive requests directly from the browser.

It is an organizational object that holds route definitions.


prefix="/documents"

This prefix is automatically added to every route registered on this router.

The route decorator says:

@router.get("/{document_id}")

FastAPI combines:

Router prefix: /documents
Route path: /{document_id}

The resulting application path is:

/documents/{document_id}

Therefore, this request matches:

GET /documents/101

This request does not:

GET /101

The prefix avoids repeating /documents on every route.

If the module eventually contains:

@router.get("/")
async def list_documents():
...
@router.get("/{document_id}")
async def document_page(document_id: int):
...
@router.post("/")
async def create_document():
...
@router.delete("/{document_id}")
async def delete_document(document_id: int):
...

the final paths become:

GET /documents/
GET /documents/{document_id}
POST /documents/
DELETE /documents/{document_id}

The router groups routes around a resource or feature.


tags=["documents"]

Tags primarily organize the generated OpenAPI documentation.

When you visit:

http://127.0.0.1:8000/docs

FastAPI groups these routes under a section named:

documents

Tags do not create security.

They do not restrict access.

They do not alter the URL.

They are descriptive metadata for OpenAPI and the interactive documentation interface.

This is an important recurring distinction:

Some FastAPI configuration affects runtime behavior; other configuration describes the application.

The prefix affects route matching.

The tag affects documentation organization.


The decorator is now:

@router.get(
"/{document_id}",
response_class=HTMLResponse,
)

During module import, this tells the router object:

Register document_page as the handler for a GET request whose router-relative path matches /{document_id}.

The decorator still runs during startup.

The function body still runs only when a request matches.

At startup:

@router.get(...)

registers the function.

During a request:

document_page(...)

executes.

Using an APIRouter does not change that distinction.


Inside app/routers/documents.py, we write:

from ..data import documents_by_id

The current module is:

app.routers.documents

One dot would start from:

app.routers

Two dots move up to:

app

The import therefore means:

From app.data, import documents_by_id.

The same applies to:

from ..security import (
get_authenticated_user,
user_can_view_document,
)

These relative imports express relationships within the same application package.

The equivalent absolute imports would be:

from app.data import documents_by_id
from app.security import (
get_authenticated_user,
user_can_view_document,
)

Both styles can work. Consistency matters more than choosing one universally “correct” style.


Now we assemble the complete application:

from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
from .routers import documents
app = FastAPI()
app.add_middleware(
SessionMiddleware,
secret_key="replace-this-with-a-random-secret",
session_cookie="app_session",
same_site="lax",
https_only=False,
)
app.include_router(documents.router)
@app.get("/")
async def home():
return {
"message": "Document Review Application",
}

main.py is now small.

This assembly excerpt shows the document router. The login routes from lesson 3 must also remain registered if the application is to provide /login; moving document routes does not register or recreate authentication routes automatically.

Its job is application assembly:

  1. Create the FastAPI application.
  2. Add middleware.
  3. Include feature routers.
  4. Optionally define a few top-level routes.

This is the application’s composition root: the place where the major components are connected.


from .routers import documents

This imports the module:

app.routers.documents

We import the module itself rather than importing only its router variable.

Why?

As the application grows, several modules will probably contain a variable named router:

documents.router
users.router
auth.router
admin.router

If we did this:

from .routers.documents import router
from .routers.users import router

the second import would overwrite the first name in main.py.

After both imports, router would refer only to the users router.

Importing the modules preserves clear names:

from .routers import documents, users
app.include_router(documents.router)
app.include_router(users.router)

We can immediately see which router is being included.


The critical line is:

app.include_router(documents.router)

This tells the main FastAPI application:

Include all routes registered on the documents router as routes belonging to this application.

Before this line, the route exists on:

documents.router

After inclusion, the main application knows about:

GET /documents/{document_id}

FastAPI’s documentation describes include_router() as adding the routes from an APIRouter to the main application. Router inclusion happens during application setup and does not add a separate network hop to each request. (FastAPI larger-applications guide)

That means the runtime path is not:

Browser
→ main application
→ network request to documents router
→ route

It is:

Browser
→ one FastAPI application
→ one combined routing table
→ route

The router is modular in the source code, but unified in the running application.


Suppose the server loads the application using:

app.main:app

Python performs the following startup sequence.

It executes the imports at the top of main.py.

This line triggers it:

from .routers import documents

Python opens and executes documents.py.

It loads:

APIRouter
HTTPException
Request
HTMLResponse
RedirectResponse
documents_by_id
get_authenticated_user
user_can_view_document

Importing data.py creates the dictionaries.

Importing security.py defines its helper functions.

router = APIRouter(
prefix="/documents",
tags=["documents"],
)

5. The decorator registers the document route

Section titled “5. The decorator registers the document route”
@router.get("/{document_id}")

The router now contains the document-page route.

The document_page() body does not execute.

Python creates the primary application:

app = FastAPI()
app.add_middleware(SessionMiddleware, ...)
app.include_router(documents.router)

The main application now contains the document route.

@app.get("/")

The application is fully assembled and ready to receive traffic.


Now assume the browser requests:

GET /documents/101 HTTP/1.1
Cookie: app_session=...

At this point, the Python modules have already been imported.

The server does not ordinarily reopen and reread all four files for every request.

The runtime sequence is:

  1. The server receives the request.
  2. SessionMiddleware verifies and decodes the cookie.
  3. The middleware places session data on the request.
  4. FastAPI checks the main application’s routing table.
  5. It matches GET /documents/{document_id}.
  6. It converts "101" into integer 101.
  7. It calls document_page().
  8. The route authenticates the user.
  9. The route retrieves the document.
  10. The authorization policy checks firm ownership.
  11. The route returns HTML.
  12. The response travels back through middleware.
  13. The server sends it to the browser.

FastAPI does not care that document_page() was defined in a different file.

Python function objects retain a reference to the code that defines them. Once the function has been registered, FastAPI can call it normally.


APIRouter changes source-code organization.

It gives us:

  • Smaller files
  • Feature-focused modules
  • Shared URL prefixes
  • Organized API documentation
  • Router-level configuration
  • Easier navigation through the codebase

It does not change:

  • HTTP
  • Browser behavior
  • Middleware mechanics
  • Authentication
  • Authorization
  • Response delivery
  • The meaning of a route function

The browser has no awareness of Python files.

It requests:

/documents/101

It does not request:

app/routers/documents.py

The filesystem organization exists only inside the server application.


A single file is not inherently wrong.

For a tiny application, this can be perfectly reasonable:

main.py

Prematurely creating dozens of modules can make a small project harder to understand.

But once main.py begins collecting unrelated features, routers provide useful boundaries.

A practical trigger is when you can identify clear groups:

auth
users
documents
firms
admin
billing
reports

Each group can receive its own router.

For the kind of modular monolith you prefer, a sensible structure might eventually become:

app/
├── main.py
├── database.py
├── models/
├── schemas/
├── services/
├── templates/
└── routers/
├── auth.py
├── firms.py
├── documents.py
├── reviews.py
└── admin.py

That remains one application and one deployment.

It is not a collection of microservices.


Because the file is called:

routers/documents.py

it should primarily contain HTTP-facing orchestration:

  • Path declarations
  • Request parameters
  • Response types
  • Redirects
  • HTTP errors
  • Calls to dependencies and services

It should not eventually contain all document-processing logic.

For example, this would make the route responsible for too much:

@router.post("/{document_id}/review")
async def review_document(document_id: int):
# Load PDF
# Rotate pages
# Extract text
# Call AI model
# Parse output
# Calculate scores
# Save results
# Send notification
# Build response

The router should eventually coordinate those operations:

result = review_service.review_document(
document_id=document_id,
user=current_user,
)

The route handles HTTP.

The service handles the business workflow.

We have not introduced the service layer yet, but APIRouter creates the first clean structural boundary.


A healthy import direction looks like this:

main.py
↓
routers/documents.py
↓
security.py and data.py

The lower-level modules should not import main.py.

For example, documents.py should not do this:

from ..main import app

That would create a loop:

main imports documents
documents imports main

Python may then encounter modules that are only partially initialized.

This often produces confusing import errors.

APIRouter avoids the need for the feature module to import the main application.

The documents module creates its own router:

router = APIRouter()

Then main.py imports and includes that router:

app.include_router(documents.router)

The dependency direction remains one-way.


We used:

router = APIRouter(
prefix="/documents",
tags=["documents"],
)

An APIRouter can also receive configuration that applies to every route it contains, including:

  • Dependencies
  • Default responses
  • Deprecation status
  • Response classes
  • Callbacks

For example:

router = APIRouter(
prefix="/documents",
tags=["documents"],
responses={
404: {
"description": "Document not found",
}
},
)

This does not automatically raise a 404.

It documents that routes in this router may produce one.

Likewise, router-level dependencies can enforce shared requirements across every route in a router.

We’ll examine that carefully when we introduce Depends.


At startup:

Python imports documents.py
↓
documents.py creates an APIRouter
↓
Decorators register document routes
↓
main.py creates the FastAPI application
↓
main.py adds middleware
↓
main.py includes documents.router
↓
The application has one combined route table

During a request:

Browser requests /documents/101
↓
SessionMiddleware reconstructs the session
↓
Main FastAPI application matches the route
↓
document_page() runs
↓
Authentication identifies the user
↓
Authorization checks document ownership
↓
HTMLResponse travels back to the browser

APIRouter separates route definitions in the source code while preserving one unified application at runtime.

main.py becomes the assembly point.

Feature modules define their own related routes.

app.include_router() connects those routes to the application during startup.

The browser still sees one website, one URL space, and one HTTP request-response cycle.

In the next tutorial, we’ll introduce Depends and replace this manual authentication call:

user = get_authenticated_user(request)

with a declarative requirement in the route signature.