FastAPI学习与实践(二) 路由总结
FastAPI 的路由系统是其核心组件之一,负责将客户端请求(如 HTTP GET、POST 等)映射到具体的处理函数(也叫“视图函数”或“端点”)。下面是 FastAPI 路由相关的知识总结,涵盖基本使用、进阶功能、最佳实践等。
🧱 基础知识
1. 路由定义方式
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def say_hello():
return {"message": "Hello, World!"}
常见方法装饰器:
-
@app.get(path) -
@app.post(path) -
@app.put(path) -
@app.delete(path) -
@app.patch(path)
2. 路径参数
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
-
可以使用类型注解自动转换为 int、str、float 等。
-
如果类型不匹配会自动返回 422 错误。
3. 查询参数
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
-
/items/?skip=5&limit=20
4. 请求体(Body)
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
🪢 路由组织
5. APIRouter:模块化路由
from fastapi import APIRouter
router = APIRouter()
@router.get("/users")
def list_users():
return ["user1", "user2"]
# 在主应用中引入
app.include_router(router, prefix="/api", tags=["User APIs"])
-
prefix: 添加路由前缀,如/api/users -
tags: 自动分组出现在 Swagger 文档中
6. 路由参数校验(Query, Path)
from fastapi import Query, Path
@app.get("/items/{item_id}")
def get_item(
item_id: int = Path(..., ge=1), # 必须 >= 1
q: str = Query(None, max_length=50) # 可选,最多50字符
):
return {"item_id": item_id, "q": q}
🔐 路由高级特性
7. 路由依赖注入(Depends)
from fastapi import Depends
def common_params(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
@app.get("/items/")
def list_items(params: dict = Depends(common_params)):
return params
-
可以用于参数复用、认证、权限检查等。
8. 路由中间件(中间处理逻辑)
虽然 FastAPI 本身用的是 Starlette 的中间件系统,但你也可以在路由层封装依赖或写装饰器。
🧰 实用补充
9. 自定义状态码 & 响应模型
from fastapi import status
from fastapi.responses import JSONResponse
@app.post("/create", status_code=status.HTTP_201_CREATED)
def create_resource():
return JSONResponse(content={"result": "ok"}, status_code=201)
10. 响应模型校验
class ItemOut(BaseModel):
name: str
price: float
@app.get("/item/", response_model=ItemOut)
def get_item():
return {"name": "apple", "price": 2.5, "extra": "hidden"} # extra 不会出现在响应中
✅ FastAPI 路由最佳实践总结
| 做法 | 建议 |
|---|---|
使用 APIRouter |
模块化结构更清晰,便于维护 |
配置 tags |
文档更清晰、分类明确 |
| 路由参数加类型注解 | 自动校验、提示更友好 |
| 使用 Pydantic 校验请求体 | 防止脏数据 |
使用 Depends 抽取公共逻辑 |
权限、数据库连接等 |
使用 response_model |
限制字段、防止泄漏 |

浙公网安备 33010602011771号