Skip to main content
As your application grows, keeping all API endpoints in a single main.py file becomes unmaintainable. FastAPI provides the APIRouter class to split routes into clean, self-contained files that can be easily plugged into the main application.

1. Modular Router Architecture

Instead of having a monolithic main.py, we organize routes by domain (e.g. employees, departments). The main app acts as a hub that imports and attaches (includes) these sub-routers.

2. Creating a Sub-Router

Let’s implement a clean sub-router for handling employee-related endpoints. Create a file named routers/employees.py (ensure the parent folder exists):

Explaining the APIRouter parameters:

  • prefix="/employees": Automatically prefixes all routes in this file. So @router.get("/") becomes accessible via /employees/, and @router.get("/{emp_id}") becomes /employees/{emp_id}.
  • tags=["Employees"]: Groups these endpoints under a dedicated “Employees” section in the auto-generated Swagger UI documentation.

3. Registering Routers in main.py

Once a router is defined, you must register it in the main application file using app.include_router().

4. Scalable Folder Layout

For a modular project, arrange your folders like this:
This structure makes it incredibly simple to add new resource modules (e.g., adding chats.py or payroll.py later as our Employee Management System grows) without cluttering our main application entrypoint.