Full answer
Putting every endpoint in main.py works for a demo and becomes unmanageable at 40 endpoints. APIRouter splits the app by feature.
A typical layout:
app/
main.py # creates FastAPI(), includes routers, lifespan
routers/
students.py # router = APIRouter()
fees.py
schemas/ # Pydantic models
services/ # business logic
db.py # engine, session dependency
deps.py # shared dependencies (current user, pagination)
In a router module:
router = APIRouter(prefix="/students", tags=["students"])
@router.get("/{roll_no}")
def get_student(roll_no: int): ...In main.py:
app.include_router(students.router)
app.include_router(fees.router, prefix="/fees", dependencies=[Depends(require_staff)])What include_router and APIRouter(...) can set for all routes in the group:
prefix: path prefix (must start with/and not end with/).tags: grouping in/docs.dependencies: run for every route, such as authentication. Their return values are not passed to handlers; use them for checks.responses: shared documented error responses.deprecated,include_in_schema.
Values from both the router and the include_router call are combined, so you can set tags in the module and a version prefix like /api/v1 in main.py.
Routers can nest: an api_v1 router includes students and fees routers, and the app includes api_v1 with prefix /api/v1. That makes API versioning straightforward.
Keep routers thin: parse input, call a service function, return a response model. Business logic in services is easier to test and reuse from background jobs.
from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
# routers/students.py
students = APIRouter(prefix="/students", tags=["students"])
@students.get("/{roll_no}")
def get_student(roll_no: int):
return {"roll_no": roll_no, "name": "Kabir"}
# routers/fees.py
fees = APIRouter(tags=["fees"])
@fees.get("/due")
def fees_due():
return {"due": 4500}
# deps.py
def require_staff(x_role: str = Header(default="student")):
if x_role != "staff":
raise HTTPException(status_code=403, detail="Staff only")
# main.py
api_v1 = APIRouter(prefix="/api/v1")
api_v1.include_router(students)
api_v1.include_router(fees, prefix="/fees", dependencies=[Depends(require_staff)])
app = FastAPI()
app.include_router(api_v1)
c = TestClient(app)
print(c.get("/api/v1/students/12").json())
print(c.get("/api/v1/fees/due").status_code, c.get("/api/v1/fees/due", headers={"X-Role": "staff"}).json())
print(sorted(app.openapi()["paths"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'roll_no': 12, 'name': 'Kabir'} 403 {'due': 4500} ['/api/v1/fees/due', '/api/v1/students/{roll_no}']
Key points
- APIRouter groups routes per feature
- include_router sets prefix, tags, dependencies, responses
- Router-level dependencies suit auth checks
- Routers nest, which helps versioning
- Keep routers thin and logic in services
Common mistakes
- Keeping every endpoint in main.py
- Ending a prefix with a slash, which produces double slashes
- Expecting router-level dependency return values to reach handlers
- Importing the app object into router modules and creating circular imports
Follow-ups
- How would you version an API as /api/v1 and /api/v2 with shared code?
- Where would you put authentication that applies to a whole module?
- How do you avoid circular imports between routers and dependencies?
Tips
- Sketch a folder layout
- Explain what include_router parameters apply to
- Mention keeping business logic out of route functions