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 monolithicmain.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
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
Createrouters/departments.py:
main.py:
Scalable Folder Layout
For a modular project, organise your folders like this:Router-Level Dependencies
Apply a dependency to every route in a router at once — for example, requiring authentication for all admin endpoints:/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:
/api/v1 and /api/v2 with different prefixes.