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 routesDocument routesUser routesAdmin routesDatabase setupSecurity functionsServicesMiddlewareConfigurationToday 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.
The new file structure
Section titled “The new file structure”Our small application will now look like this:
app/├── __init__.py├── main.py├── data.py├── security.py└── routers/ ├── __init__.py └── documents.pyEach 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)
app/data.py
Section titled “app/data.py”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.
app/security.py
Section titled “app/security.py”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_idstarts with one dot.
That dot means:
Start from the current Python package,
app.
The complete import target is conceptually:
app.data.users_by_idsecurity.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?
app/routers/documents.py
Section titled “app/routers/documents.py”Now we create the document router:
from html import escape
from fastapi import APIRouter, HTTPException, Requestfrom fastapi.responses import HTMLResponse, RedirectResponse
from ..data import documents_by_idfrom ..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:
appNow we register it on:
routerCreating the router
Section titled “Creating the router”router = APIRouter( prefix="/documents", tags=["documents"],)APIRouter is a Python class.
Calling it creates an object:
routerThat 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.
The prefix
Section titled “The prefix”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: /documentsRoute path: /{document_id}The resulting application path is:
/documents/{document_id}Therefore, this request matches:
GET /documents/101This request does not:
GET /101The 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.
The tags
Section titled “The tags”tags=["documents"]Tags primarily organize the generated OpenAPI documentation.
When you visit:
http://127.0.0.1:8000/docsFastAPI groups these routes under a section named:
documentsTags 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.
Registering a route on the router
Section titled “Registering a route on the router”The decorator is now:
@router.get( "/{document_id}", response_class=HTMLResponse,)During module import, this tells the router object:
Register
document_pageas the handler for aGETrequest 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.
Why the imports use two dots
Section titled “Why the imports use two dots”Inside app/routers/documents.py, we write:
from ..data import documents_by_idThe current module is:
app.routers.documentsOne dot would start from:
app.routersTwo dots move up to:
appThe import therefore means:
From
app.data, importdocuments_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_idfrom app.security import ( get_authenticated_user, user_can_view_document,)Both styles can work. Consistency matters more than choosing one universally “correct” style.
app/main.py
Section titled “app/main.py”Now we assemble the complete application:
from fastapi import FastAPIfrom 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:
- Create the FastAPI application.
- Add middleware.
- Include feature routers.
- Optionally define a few top-level routes.
This is the application’s composition root: the place where the major components are connected.
Importing the documents module
Section titled “Importing the documents module”from .routers import documentsThis imports the module:
app.routers.documentsWe 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.routerusers.routerauth.routeradmin.routerIf we did this:
from .routers.documents import routerfrom .routers.users import routerthe 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.
Including the router
Section titled “Including the router”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.routerAfter 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→ routeIt is:
Browser→ one FastAPI application→ one combined routing table→ routeThe router is modular in the source code, but unified in the running application.
Startup execution order
Section titled “Startup execution order”Suppose the server loads the application using:
app.main:appPython performs the following startup sequence.
1. Python begins importing app.main
Section titled “1. Python begins importing app.main”It executes the imports at the top of main.py.
2. Python imports app.routers.documents
Section titled “2. Python imports app.routers.documents”This line triggers it:
from .routers import documentsPython opens and executes documents.py.
3. documents.py imports its requirements
Section titled “3. documents.py imports its requirements”It loads:
APIRouterHTTPExceptionRequestHTMLResponseRedirectResponsedocuments_by_idget_authenticated_useruser_can_view_documentImporting data.py creates the dictionaries.
Importing security.py defines its helper functions.
4. documents.py creates its router
Section titled “4. documents.py creates its router”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.
6. Control returns to main.py
Section titled “6. Control returns to main.py”Python creates the primary application:
app = FastAPI()7. Middleware is registered
Section titled “7. Middleware is registered”app.add_middleware(SessionMiddleware, ...)8. The document router is included
Section titled “8. The document router is included”app.include_router(documents.router)The main application now contains the document route.
9. The home route is registered
Section titled “9. The home route is registered”@app.get("/")The application is fully assembled and ready to receive traffic.
Request-time execution
Section titled “Request-time execution”Now assume the browser requests:
GET /documents/101 HTTP/1.1Cookie: 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:
- The server receives the request.
SessionMiddlewareverifies and decodes the cookie.- The middleware places session data on the request.
- FastAPI checks the main application’s routing table.
- It matches
GET /documents/{document_id}. - It converts
"101"into integer101. - It calls
document_page(). - The route authenticates the user.
- The route retrieves the document.
- The authorization policy checks firm ownership.
- The route returns HTML.
- The response travels back through middleware.
- 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.
What APIRouter changes
Section titled “What APIRouter changes”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/101It does not request:
app/routers/documents.pyThe filesystem organization exists only inside the server application.
Why not put everything in main.py?
Section titled “Why not put everything in main.py?”A single file is not inherently wrong.
For a tiny application, this can be perfectly reasonable:
main.pyPrematurely 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:
authusersdocumentsfirmsadminbillingreportsEach 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.pyThat remains one application and one deployment.
It is not a collection of microservices.
A router is not a service layer
Section titled “A router is not a service layer”Because the file is called:
routers/documents.pyit 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 responseThe 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.
Avoiding circular imports
Section titled “Avoiding circular imports”A healthy import direction looks like this:
main.py ↓routers/documents.py ↓security.py and data.pyThe lower-level modules should not import main.py.
For example, documents.py should not do this:
from ..main import appThat would create a loop:
main imports documentsdocuments imports mainPython 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.
Router-level configuration
Section titled “Router-level configuration”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.
The complete mental model
Section titled “The complete mental model”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 tableDuring 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 browserThe central idea
Section titled “The central idea”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.