fastapi-router-creator
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFastAPI Router Creator
FastAPI 路由器创建指南
This skill guides the creation of modular, organized FastAPI routers, emphasizing maintainability and scalability.
本技能指导你创建模块化、结构化的FastAPI路由器,重点关注可维护性和可扩展性。
Routing Strategies
路由策略
1. Modular Router Pattern (Standard)
1. 模块化路由模式(标准方案)
The most common and recommended approach for FastAPI.
Structure:
src/api/v1/endpoints/
├── users.py
├── items.py
└── auth.pyImplementation:
src/api/v1/endpoints/users.pypython
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
async def get_users():
...src/api/v1/api.pypython
from fastapi import APIRouter
from src.api.v1.endpoints import users, items
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(items.router, prefix="/items", tags=["items"])这是FastAPI最常用且推荐的方案。
结构:
src/api/v1/endpoints/
├── users.py
├── items.py
└── auth.py实现方式:
src/api/v1/endpoints/users.pypython
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
async def get_users():
...src/api/v1/api.pypython
from fastapi import APIRouter
from src.api.v1.endpoints import users, items
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(items.router, prefix="/items", tags=["items"])2. File-Based Routing (fastapi-router)
2. 基于文件的路由(fastapi-router方案)
For a Next.js-like experience where file structure dictates URLs. (Requires library or custom walker).
fastapi-routerStructure:
src/app/
├── api/
│ ├── users/
│ │ ├── route.py # Handles /api/users
│ │ └── [id]/
│ │ └── route.py # Handles /api/users/{id}提供类似Next.js的体验,文件结构直接决定URL路径(需要库或自定义遍历器)。
fastapi-router结构:
src/app/
├── api/
│ ├── users/
│ │ ├── route.py # 处理 /api/users
│ │ └── [id]/
│ │ └── route.py # 处理 /api/users/{id}Best Practices
最佳实践
- Prefixing: Use prefixes at the router include level, not inside every endpoint decorator.
- Tags: Use tags to group endpoints in OpenAPI docs.
- Dependencies: Apply dependencies (like auth) at the router level if they apply to all endpoints in that router.
python
router = APIRouter(dependencies=[Depends(get_current_active_user)]) - Version: Namespace routers by API version (,
v1).v2
- 路由前缀:在引入路由器时设置前缀,而非在每个端点装饰器中单独设置。
- 标签设置:使用标签在OpenAPI文档中对端点进行分组。
- 依赖管理:如果某个依赖(如认证)适用于路由器下的所有端点,就在路由器级别统一配置。
python
router = APIRouter(dependencies=[Depends(get_current_active_user)]) - 版本管理:通过API版本(如、
v1)对路由器进行命名空间划分。v2