As your FastAPI application grows, it’s crucial to maintain a well-organized and modular structure. One effective way to achieve this is by using the APIRouter class. This class allows you to group related path operations together, making your code more manageable and easier to understand.
Creating APIRouter Instances
To create an APIRouter instance, import it from the fastapi module:
Python
from fastapi import APIRouter
Then, create an instance with an optional prefix and tags:
Python
router = APIRouter(
prefix="/users",
tags=["Users"]
)
- The
prefixargument specifies the base path for the router. - The
tagsargument is used for documentation purposes and can be helpful for grouping related endpoints.
Defining Path Operations
You can define path operations within the APIRouter instance using the familiar decorators:
Python
@router.get("/")
def read_users():
# ...
@router.post("/")
def create_user(user: User):
# ...
Including Routers in the Main Application
To include a router in your main application, use the include_router method:
Python
from app import users_router
app = FastAPI()
app.include_router(users_router.router)
Benefits of Using APIRouter
- Modularity: Encapsulate related endpoints into separate modules.
- Reusability: Create reusable routers that can be imported and included in different parts of your application.
- Documentation: Use tags to organize endpoints and improve API documentation.
- Maintainability: Make it easier to manage and update your API as it grows.
Example:
Python
# users/routes.py
from fastapi import APIRouter, HTTPException
from app.models import User
router = APIRouter(
prefix="/users",
tags=["Users"]
)
@router.get("/")
def read_users():
return {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
@router.post("/")
def create_user(user: User):
# ...
Python
# main.py
from fastapi import FastAPI
from app import users_router
app = FastAPI()
app.include_router(users_router.router)
By effectively using APIRouter, you can structure your FastAPI application in a more organized and maintainable way. This will make it easier to develop, test, and scale your API as your project grows.
