Script Valley
FastAPI: Build Production Python APIs
FastAPI FoundationsLesson 1.5

How to structure a FastAPI project with routers and multiple files

APIRouter, include_router, prefix and tags, project file structure, separating concerns, router dependencies, multiple route files

Project Structure with APIRouter

As your API grows, putting all routes in main.py becomes unmanageable. APIRouter lets you split routes across files and mount them with a shared prefix.

Recommended file layout

app/
  main.py
  routers/
    users.py
    items.py
  models.py
  database.py

Define a router

# app/routers/users.py
from fastapi import APIRouter

router = APIRouter(prefix="/users", tags=["users"])

@router.get("/")
def list_users():
    return [{"id": 1, "name": "Alice"}]

@router.get("/{user_id}")
def get_user(user_id: int):
    return {"id": user_id}

The prefix is prepended to every route in that router. tags groups the routes under a section in Swagger UI.

Mount routers in main.py

# app/main.py
from fastapi import FastAPI
from app.routers import users, items

app = FastAPI()

app.include_router(users.router)
app.include_router(items.router)

@app.get("/health")
def health():
    return {"status": "ok"}

You can pass additional prefix, tags, or dependencies to include_router to override or extend what the router declares. This lets you add auth middleware to an entire router without touching its individual routes.