FastAPI 元数据配置:定制 OpenAPI 文档和界面

FastAPI 元数据配置:定制 OpenAPI 文档和界面


推荐阅读 📚🎓🧑‍🏫

[1] 一起学Python 专栏:深入探讨 Python 编程,涵盖基础与进阶内容,以及 NumPyPandasMatplotlibDockerLinux 等实用技术。


FastAPI 提供了灵活的元数据配置选项,帮助开发者自定义 API 文档。通过设置 titledescriptionversion 等元数据,可以为 API 提供详细的介绍。同时,FastAPI 支持使用标签(tags)对路由进行分类和排序,使得文档更加结构化。开发者还可以修改 OpenAPI 和文档的 URL 路径,例如通过 openapi_urldocs_urlredoc_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"}]

六 源码地址

详情见:GitHub FastApiProj

七 参考

[1] FastAPI 官方文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码不忘补水

感谢有你,让我的创作更有价值!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值