0%

FastAPI自学教程(49) - 路径操作高级配置

1. OpenAPI 的 operationId 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI
from fastapi.routing import APIRoute

app = FastAPI()

@app.get("/items/", operation_id="custom_operation_id")
async def read_items():
return [{"item_name": "Foo"}]

def use_route_names_as_operation_ids(app: FastAPI):
for route in app.routes:
if isinstance(route, APIRoute):
route.operation_id = route.name # 使用路由函数名作为operation_id

use_route_names_as_operation_ids(app)
  • 通过operation_id参数自定义接口在OpenAPI中的唯一标识符
  • 支持遍历路由将函数名自动设为operation_id(需在路由注册后执行)
  • 注意事项:
    • 需保证所有路径操作函数名称唯一
    • 修改operation_id后需重新生成客户端代码

2. 从 OpenAPI 排除路径操作

1
2
3
@app.get("/hidden-api", include_in_schema=False)
async def hidden_endpoint():
return {"message": "此接口不会出现在API文档"}
  • 使用include_in_schema=False隐藏指定接口
  • 适用场景:内部测试接口/未完成的功能接口

3. 文档字符串高级处理

1
2
3
4
5
6
7
8
9
10
11
12
13
@app.post("/items/", summary="创建项目")
async def create_item(item: Item):
"""
创建项目的完整说明:
- **name**: 必填项
- **description**: 支持Markdown格式
- **price**: 必须大于0

\f
内部参数说明(仅开发者可见):
- created_by: 自动记录创建人
"""
return item
  • 使用\f(换页符)分隔公开文档与内部注释
  • 效果:
      graph TD
      A[接口文档] --> B[显示summary]
      A --> C[显示\f前描述]
      A --> D[隐藏\f后内容]

4. 其他高级配置参数

4.1 接口标签分类

1
2
3
@app.get("/users/", tags=["用户管理", "核心接口"])
async def get_users():
return [{"username": "john"}]
  • tags参数实现接口分组,支持多标签

4.2 接口描述增强

1
2
3
4
5
6
7
8
@app.post(
"/products/",
summary="创建商品",
description="### 高级说明\n- 支持批量创建\n- 自动生成SKU编码",
response_description="返回创建成功的商品ID"
)
async def create_product():
return {"product_id": 123}
  • summary:简洁说明(显示在接口列表)
  • description:详细说明(支持Markdown)
  • response_description:响应数据说明

4.3 废弃接口标记

1
2
3
@app.get("/old-api", deprecated=True)
async def deprecated_api():
return {"warning": "请使用/v2/new-api替代"}
  • deprecated=True在文档中标记为废弃接口

测试命令查看文档效果:

1
uvicorn main:app --reload