APIRouter and application structure

Difficulty: Intermediate

Question

How do you organize a large FastAPI application using APIRouter?

Answer

APIRouter is a mini-application that groups related routes. It works exactly like the FastAPI app instance but is included into the main app with app.include_router().

Benefits:

  • Split routes into multiple files/modules
  • Apply shared prefix, tags, dependencies, and responses to all routes in the router
  • Keep each domain area (users, items, orders) in separate files

Typical structure:

app/
  main.py          # FastAPI instance, includes routers
  routers/
    users.py       # APIRouter for /users
    items.py       # APIRouter for /items
  models/          # Pydantic models
  database.py      # DB setup

Code examples

APIRouter usage

# routers/users.py
from fastapi import APIRouter, Depends

router = APIRouter(
    prefix="/users",
    tags=["users"],
    responses={404: {"description": "Not found"}}
)

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

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

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

app = FastAPI()
app.include_router(users.router)
app.include_router(items.router, prefix="/api/v1")  # override prefix

Key points

  • Router-level `dependencies` apply to all routes in the router
  • `app.include_router()` can add additional prefix, tags, or dependencies on top of the router's own
  • Routers can include other routers for deep nesting

Common follow-up questions

  • How do you apply authentication to an entire router?
  • What is the recommended project structure for a production FastAPI app?

Interview tips

  • Show the recommended project structure alongside the APIRouter explanation

Concepts covered

APIRouter, modular structure, prefix, tags

More FastAPI Interview questions