Skip to main content
As your application grows, keeping every route in a single main.py file quickly becomes unmaintainable. A file that starts at 50 lines can reach 500 lines by the time you’ve added employees, departments, authentication, and payroll endpoints. FastAPI’s APIRouter class solves this by letting you define routes in separate, self-contained files and then plug them into your main application with a single line. This lesson shows you how to split, organise, and register routers cleanly.

Modular Router Architecture

Instead of a monolithic main.py, you organise routes by domain. The main app acts as a hub that imports and attaches these sub-routers:

Creating a Sub-Router

1

Create the routers folder

2

Create the employee router file

Create routers/employees.py:
3

Register the router in main.py

4

Run the server

FastAPI maps all employee routes automatically:
  • GET /employees/
  • GET /employees/{emp_id}
  • POST /employees/

Understanding APIRouter Parameters

The prefix means you write shorter routes in each file. @router.get("/") is the employee list, and @router.get("/{emp_id}") is the single employee — the /employees prefix is added automatically when you register the router.

Adding a Second Router

Create routers/departments.py:
Register it in main.py:

Scalable Folder Layout

For a modular project, organise your folders like this:
Adding a new resource is now just two steps: create routers/payroll.py and add app.include_router(payroll.router) to main.py. Every other file stays unchanged.

Router-Level Dependencies

Apply a dependency to every route in a router at once — for example, requiring authentication for all admin endpoints:
Both /admin/stats and /admin/employees/{id} will require authentication without you having to add Depends(get_current_user) to each function individually.

include_router Options

You can override or extend router settings when registering:
This is useful for API versioning — you can include the same router twice under /api/v1 and /api/v2 with different prefixes.