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 monolithicmain.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 namedrouters/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:chats.py or payroll.py later as our Employee Management System grows) without cluttering our main application entrypoint.