闷骚熊猫

导航

APIRouter

在 FastAPI 中, APIRouter 是组织多路由模块的核心工具, 尤其适用于中大型项目。 以下是模块化路由的标准实践:

基础结构示例
text
project / ├──main.py

└── apps / ├──__init__.py

└── routers / ├──__init__.py

├── users.py└── items.py
路由定义示例(apps / routers / users.py)
python
from fastapi
import APIRouter

router = APIRouter(prefix = "/users", tags = ["用户管理"])

@router.get("/")
async def get_users():
return [{
"name": "Alice"
}, {
"name": "Bob"
}]

@router.post("/create")
async def create_user(user: dict):
return {
"status": "created",
"user": user
}
主程序集成(main.py)
python
from fastapi
import FastAPI
from apps.routers
import users, items

app = FastAPI()

# 挂载路由模块
app.include_router(users.router)
app.include_router(
items.router,
prefix = "/items",
tags = ["商品管理"],
dependencies = [...] # 可添加统一依赖
)
高级配置技巧:
路径聚合: 使用 prefix 参数自动添加路径前缀
标签分组: 通过 tags 参数实现Swagger文档分类
统一依赖: 为整个路由组设置通用依赖项
响应定制: 支持路由级别的响应模型配置
版本控制: 结合 Prefix 实现 API 版本管理
这种模式的优势:

代码解耦: 业务逻辑独立封装
团队协作: 模块化开发互不干扰
维护便捷: 功能模块定位快速
扩展灵活: 新增路由无需修改主程序

posted on 2025-03-25 11:11  闷骚熊猫  阅读(37)  评论(0)    收藏  举报