Organizing FastAPI Applications with APIRouter for Modular Routing
As FastAPI applications grow in complexity, consolidating all routes within a single file becomes cumbersome and difficult to maintain. Route distribution enables developers to seperate functionality into distinct modules, enhancing code organization and scalability. For instance, an e-commerce system might isolate user management, order procesing, and product catalog into independent modules.
FastAPI's APIRouter facilitates this by allowing the creation of sub-routes that can be integrated into the main application. The process involves two primary steps: constructing sub-routes with APIRouter and incorporating them into the primary app using include_router().
Consider a project structure where modules are housed in a dedicated directory:
├── main.py
└── modules/
├── users/
│ └── endpoints.py
└── orders/
└── endpoints.py
In the users module, define routes within endpoints.py:
# modules/users/endpoints.py
from fastapi import APIRouter
user_router = APIRouter()
@user_router.get("/profile")
def fetch_user_profile():
return {"message": "User profile data"}
Similarly, for the orders module:
# modules/orders/endpoints.py
from fastapi import APIRouter
order_router = APIRouter()
@order_router.get("/all")
def retrieve_orders():
return {"message": "List of orders"}
@order_router.get("/{order_id}")
def fetch_order_details(order_id: int):
return {"message": f"Details for order ID: {order_id}"}
In the main application file, import and include these routers:
# main.py
from fastapi import FastAPI
from modules.users.endpoints import user_router
from modules.orders.endpoints import order_router
app = FastAPI()
app.include_router(user_router, prefix="/users", tags=["User Operations"])
app.include_router(order_router, prefix="/orders", tags=["Order Management"])
The include_router method attaches the sub-routes to the main app, with prefix prepending a path segment to all routes in that router and tags grouping endpoints in the auto-generated documentation.
Launch the application with a command like uvicorn main:app --reload and navigate to http://127.0.0.1:8000/docs. The interactive documentation will display the routes under their respective tags, with paths such as /users/profile and /orders/all. Accessing /orders/5 would invoke the detail endpoint with order_id set to 5.