0%

FastAPI自学教程(45) - 元数据配置

1. 基础元数据配置

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

app = FastAPI(
title="我的API",
description="这是一个演示FastAPI元数据的示例接口文档",
version="1.0.0",
contact={
"name": "技术支持",
"email": "support@example.com"
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
}
)

@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
  • 核心配置参数:
    • title:API文档标题
    • description:接口整体描述(支持Markdown格式)
    • version:API版本号
    • contact:技术支持联系方式
    • license_info:许可证信息
  • 效果展示:
      graph TD
      A[Swagger UI] --> B[显示自定义标题]
      A --> C[显示版本号]
      A --> D[显示许可证链接]

2. 接口标签管理

1
2
3
4
5
6
7
8
@app.get(
"/users/",
tags=["用户管理", "核心接口"],
summary="获取用户列表",
description="### 高级说明\n- 支持分页查询\n- 返回数据经过加密处理"
)
async def read_users():
return [{"username": "johndoe"}]
  • 标签配置参数:
    • tags:接口分类标签(列表形式,支持多标签)
    • summary:接口简要说明(显示在接口列表)
    • description:详细说明(支持Markdown语法)
  • 标签分组效果:
      graph LR
      A[用户管理] --> B[用户列表]
      A --> C[创建用户]
      D[商品管理] --> E[商品查询]

3. OpenAPI文档定制

3.1 自定义文档路径

1
app = FastAPI(docs_url="/custom-docs", redoc_url="/custom-redoc")
  • 禁用文档:设置docs_url=Noneredoc_url=None
  • 自定义路径:避免使用默认路径增强安全性

3.2 扩展元数据字段

1
2
3
4
5
6
7
8
9
10
app = FastAPI(openapi_tags=[
{
"name": "用户管理",
"description": "用户认证和权限管理接口"
},
{
"name": "商品管理",
"description": "商品信息CRUD操作接口"
}
])
  • 为每个标签添加详细描述说明
  • 控制接口在文档中的分组顺序

4. 生产环境建议

  1. 版本控制:在URL路径中体现版本号/api/v1/items
  2. 安全信息:避免在描述中暴露敏感接口细节
  3. 文档访问:生产环境建议禁用文档或添加访问权限
  4. 响应模型:使用response_model显式声明返回数据结构
  5. 错误代码:通过responses参数补充错误码说明

测试命令查看文档:

1
2
3
4
5
# 查看Swagger UI文档
http://localhost:8000/docs

# 查看ReDoc文档
http://localhost:8000/redoc