← Back to FastAPI map
FastAPI · Advanced

Routers

Split your routes into separate APIRouter files and keep old versions working.

modules

Overview

As an API grows, a single main.py gets hard to navigate. APIRouter is a mini-app: you declare routes on it exactly as on app, together with a shared prefix, tags, dependencies, and responses. main.py then includes each router, and versioning (/api/v1, /api/v2) becomes a matter of mounting routers under different prefixes.

Key concepts

prefix
Prepended to the path of every route in the router.
tags
Group the router's routes together in /docs.
Router dependencies
Applied to every route in the router - for example, authentication for everything under /admin.
include_router
Can add a further prefix, tags, and dependencies when the router is included.

Best practices

  • Use one router per resource or domain - users, items, auth - each in its own module.
  • Keep handlers thin and call services for business logic, so routers stay about HTTP.
  • Version by prefix, and keep the old version running until clients have migrated.

APIRouter - modular structure

Creating and including routers

Routers
# routers/users.py from fastapi import APIRouter, Depends router = APIRouter( prefix="/users", tags=["users"], dependencies=[Depends(get_current_user)], # auth all routes responses={404: {"description": "Not found"}} ) @router.get("/") async def list_users(): ... @router.get("/{user_id}") async def get_user(user_id: int): ... # main.py from routers import users, items, auth app = FastAPI() app.include_router(auth.router) app.include_router(users.router) app.include_router(items.router, prefix="/api/v1") # API versioning app.include_router(v1_router, prefix="/api/v1") app.include_router(v2_router, prefix="/api/v2")

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...