FastAPI 元数据配置:定制 OpenAPI 文档和界面
推荐阅读 📚🎓🧑🏫
[1] 一起学Python 专栏:深入探讨 Python 编程,涵盖基础与进阶内容,以及 NumPy、Pandas、Matplotlib、Docker、Linux 等实用技术。
FastAPI 提供了灵活的元数据配置选项,帮助开发者自定义 API 文档。通过设置 title
、description
、version
等元数据,可以为 API 提供详细的介绍。同时,FastAPI 支持使用标签(tags)对路由进行分类和排序,使得文档更加结构化。开发者还可以修改 OpenAPI 和文档的 URL 路径,例如通过 openapi_url
、docs_url
和 redoc_url
参数自定义访问路径,或禁用默认的 Swagger UI 和 ReDoc 文档界面。利用这些配置选项,FastAPI 使得 API 文档既清晰又易于定制,提升了开发和使用的效率。
文章目录
预备课:FastAPI Swagger 文档:路径操作配置与自定义参数优化
以下示例中使用的 Python 版本为 Python 3.10.15
,FastAPI 版本为 0.115.4
。
一 示例代码
from fastapi import FastAPI
description = """
YourApp API helps you do awesome stuff.
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
app = FastAPI(
title="这是一个 title",
description=description,
summary="这是一个 summary ",
version="0.0.1",
terms_of_service="http://example.com/terms/",
contact={
"name": "这是 contact name ",
"url": "http:/your.com/contact/",
"email": "your@fast.example.com",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
}
)
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]
运行代码文件 ot01.py 来启动应用:
$ uvicorn ot01:app --reload
在 SwaggerUI 中可以查看在线文档:http://127.0.0.1:8000/docs
。
二 OpenAPI 元数据
description = """
YourApp API helps you do awesome stuff.
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
app = FastAPI(
title="这是一个 title",
description=description,
summary="这是一个 summary ",
version="0.0.1",
terms_of_service="http://example.com/terms/",
contact={
"name": "这是 contact name ",
"url": "http:/your.com/contact/",
"email": "your@fast.example.com",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
}
)
API 元数据可用于设置 OpenAPI 规范和自动 API 文档 UI 的字段:
-
title (str): API 标题
-
summary (str): API 简短摘要(自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用)
-
description (str): API 描述,可使用 Markdown
-
version (str): API 版本(如 2.5.0)
-
terms_of_service (str): 服务条款 URL(若提供,必须是 URL 格式)
-
contact
(dict): 联系信息,包含以下字段:
- name (str): 联系人/组织名称
- url (str): 联系人信息 URL(必须是 URL 格式)
- email (str): 联系人电子邮件地址
-
license_info
(dict): 许可证信息,包含以下字段:
- name (str): 许可证名称(必填)
- identifier (str): API 的 SPDX 许可证表达(自 OpenAPI 3.1.0、FastAPI 0.99.0 起可用)
- url (str): 许可证 URL(必须是 URL 格式)
Swagger UI 如下:
三 标签元数据
from fastapi import FastAPI
# 支持 markdown
tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.tiangolo.com/",
},
},
]
app = FastAPI(openapi_tags=tags_metadata)
1 使用标签
@app.get("/users/", tags=["users"])
async def get_users():
return [{"name": "Harry"}, {"name": "Ron"}]
@app.get("/items/", tags=["items"])
async def get_items():
return [{"name": "wand"}, {"name": "flying broom"}]
2 Swagger UI 效果
3 标签顺序
标签元数据字典的顺序决定了文档界面中的显示顺序。例如,尽管 users
排在 items
后,它会因在列表中位于首位而优先显示。
四 激活和禁用 OpenAPI
1 修改 openapi.json 的访问地址
app = FastAPI(openapi_url="/api/v1/openapi.json")
默认情况下,OpenAPI 模式位于 /openapi.json
,但可以通过 openapi_url
参数进行配置,例如设置为 /api/v1/openapi.json
。
2 修改 OpenAPI 的访问路径
# Swagger UI
app = FastAPI(docs_url="/your_docs")
# ReDoc
app = FastAPI(redoc_url="/your_redocs")
3 激活和禁用 OpenAPI
要禁用 OpenAPI 模式,可以设置 openapi_url=None
,这也会禁用相关文档界面。可以配置以下文档界面:
- Swagger UI:uri 访问地址
/docs
,可通过docs_url
设置 URL,设置docs_url=None
可禁用。 - ReDoc:uri 访问
/redoc
,可通过redoc_url
设置 URL,设置redoc_url=None
可禁用。
例如,禁用 ReDoc:
# Swagger UI
app = FastAPI(docs_url=None)
# ReDoc
app = FastAPI(redoc_url=None)
五 完整代码示例
from fastapi import FastAPI
description = """
YourApp API helps you do awesome stuff.
## Items
You can **read items**.
## Users
You will be able to:
* **Create users** (_not implemented_).
* **Read users** (_not implemented_).
"""
tags_metadata = [
{
"name": "users",
"description": "Operations with users. The **login** logic is also here.",
},
{
"name": "items",
"description": "Manage items. So _fancy_ they have their own docs.",
"externalDocs": {
"description": "Items external docs",
"url": "https://fastapi.tiangolo.com/",
},
},
]
# openapi_url=None 完全禁用 OpenAPI 模式
app = FastAPI(
title="这是一个 title",
description=description,
summary="这是一个 summary ",
version="0.0.1",
terms_of_service="http://example.com/terms/",
contact={
"name": "这是 contact name ",
"url": "http:/your.com/contact/",
"email": "your@fast.example.com",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
}, openapi_tags=tags_metadata, openapi_url="/api/v1/openapi.json", docs_url="/your_docs", redoc_url=None
)
@app.get("/items/")
async def read_items():
return [{"name": "Katana"}]
@app.get("/users01/", tags=["users"])
async def get_users():
return [{"name": "Harry"}, {"name": "Ron"}]
@app.get("/items02/", tags=["items"])
async def get_items():
return [{"name": "wand"}, {"name": "flying broom"}]
六 源码地址
七 参考
[1] FastAPI 官方文档