装饰器 · FastAPI 路由

FastAPI 用装饰器把函数注册为 HTTP 端点。本文聚焦路由装饰器;依赖注入见 函数-依赖-Depends,横切见 函数-中间件-middleware

0. 一句话定位

维度 内容
作用对象 函数(async/sync)
使用场景 路由
来源 第三方 fastapi
语法形式 @app.get(...) / @router.post(...)

段末注释:OpenAPI 是描述 REST API 的规范;FastAPI 根据路由装饰器与类型注解自动生成文档。

1. 做什么

按 HTTP 方法与路径绑定处理函数;解析 Path/Query/Body 参数(Pydantic + 类型注解);生成 OpenAPI schema 与 /docs 交互文档。

2. 重点参数(路由装饰器共有)

参数 类型 默认值 作用 配置建议
path str "/" URL 路径,含 {param} 占位 REST 资源用名词复数
response_model type None 响应体模型,过滤输出字段 勿返回 ORM 对象裸奔
status_code int 200/201 等 成功响应 HTTP 状态码 POST 创建常用 201
tags list[str] None OpenAPI 分组 按业务模块分 tag
summary / description str 自动 文档标题与正文 公共 API 建议手写
deprecated bool False 标记废弃 版本迁移时用
response_model_exclude_unset bool False 仅输出显式设置的字段 部分更新响应

常用方法装饰器getpostputpatchdeleteheadoptions

3. 最小可运行示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
price: float

@app.get("/")
async def root():
return {"message": "ok"}

@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
return Item(name=f"item-{item_id}", price=9.9)

@app.post("/items/", status_code=201, response_model=Item)
async def create_item(item: Item):
return item

启动:uvicorn main:app --reload

4. APIRouter 模块化

1
2
3
4
5
6
7
8
9
10
from fastapi import APIRouter

router = APIRouter(prefix="/users", tags=["users"])

@router.get("/{user_id}")
async def get_user(user_id: int):
return {"user_id": user_id}

# main.py
app.include_router(router)
APIRouter 参数 作用
prefix 该组路由统一前缀
tags 默认 OpenAPI tag
dependencies 组内所有路由共享 Depends
responses 公共响应说明

5. 常见变体

同步端点(阻塞 IO 会占线程池)

1
2
3
@app.get("/sync")
def sync_endpoint():
return {"ok": True}

多路径绑定同一函数

1
2
3
@app.api_route("/legacy", methods=["GET", "POST"])
async def legacy():
return {"ok": True}

自定义响应类

1
2
3
4
5
from fastapi.responses import JSONResponse, StreamingResponse

@app.get("/raw")
async def raw():
return JSONResponse({"a": 1})

6. 适用 / 不适用

适用

  • REST/HTTP API、需要自动 OpenAPI 文档
  • 与 Pydantic 模型、Depends 组合的分层服务

不适用

  • 纯 CLI、无 HTTP → 不必 FastAPI
  • 非 HTTP 协议主路径 → 考虑 gRPC、WebSocket 专章

7. 易踩坑

  • 路径参数名与函数参数名须一致:/items/{item_id}item_id: int
  • 路由注册顺序影响匹配;更具体的路径应优先定义
  • response_model 会过滤未在模型中的字段,调试时「字段消失」先查此项
  • async def 内勿写阻塞调用(time.sleep、同步 DB),会阻塞事件循环

8. 参考

-------------本文结束感谢您的阅读-------------