FastAPI(36)- FastAPI 的元数据配置和文档 URL

Metadata 元数据

可以给 API 添加元数据

 

实际栗子

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/9/26 8:53 下午
# file: 31_metadata.py
"""
import uvicorn
from fastapi import FastAPI

description = """
ChimichangApp 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="ChimichangApp",
    description=description,
    version="0.0.1",
    terms_of_service="http://example.com/terms/",
    contact={
        "name": "Deadpoolio the Amazing",
        "url": "https://www.cnblogs.com/poloyy/",
        "email": "dp@x-force.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"}]


if __name__ == "__main__":
    uvicorn.run(app="31_metadata:app", host="127.0.0.1", port=8080, reload=True, debug=True)

 

查看 Swagger API

 

常见元数据参数

参数 类型 描述
title str API 的标题
description str API 的描述,可以使用 MarkDown 格式
version str API 的版本,是自己应用程序的版本,不是 OpenAPI 的版本
terms_of_service str 服务条款的 URL,如果提供,这必须是一个 URL
contact dict API 的联系信息,它可以包含多个字段
license_info dict API 的许可信息,它可以包含多个字段

 

contact 字段

参数 类型 描述
name str 联系人/组织的识别名称
url str 指向联系信息的 URL,必须采用 URL 格式
email str 联系人/组织的电子邮件地址,必须采用电子邮件地址的格式

 

license_info 字段

参数 类型 描述
name str 必传(如果设置了 license_info), API 的许可证名称
url str API 的许可证的 URL,必须采用 URL 格式

 

为 tags 创建元数据

之前在讲路径操作装饰器的配置项的时候,有提过 tags 这个参数,这里来讲下给不同 tags 创建元数据

from fastapi import FastAPI

tags_metadata = [
    {
        # name 要对应 tags 参数值
        "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://www.cnblogs.com/poloyy/",
        },
    },
]

# 添加 openapi_tags 参数 app
= FastAPI(openapi_tags=tags_metadata) @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"}]

 

查看 openapi_tags 参数的类型声明

openapi_tags: Optional[List[Dict[str, Any]]] = None 

Dict 组成的 List

 

查看 Swagger API 文档

 

tags 的顺序

不同标签在 tags_metadata 字典中的顺序,也定义了在 Swagger API 文档中 tags 的显示顺序

 

OpenAPI URL

  • 默认情况下,OpenAPI Schema 位于 /openapi.json
  • 但是可以使用参数 openapi_url 对其进行配置
from fastapi import FastAPI

app = FastAPI(openapi_url="/api/v1/openapi.json")


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]

 

查看 openapi_url 参数

openapi_url: Optional[str] = "/openapi.json"

默认值就是 /openapi.json

 

OpenAPI Schema 的访问地址变成

http://127.0.0.1:8080/api/v1/openapi.json

 

查看 Swagger API 文档

 

禁用 OpenAPI Schema

app = FastAPI(openapi_url=None)

 

这样会导致 Swagger API 文档也无法访问

 

两个文档 URL

docs_url: Optional[str] = "/docs",
redoc_url: Optional[str] = "/redoc",

 

Swagger API

  • 默认 /docs
  • 使用参数 docs_url 设置其 URL
  • 也可以通过设置 docs_url=None 来禁用它

 

ReDoc

  • 默认 /redoc
  • 使用参数 redoc_url 设置其 URL
  • 也可以通过设置 redoc_url=None 来禁用它

 

实际代码

from fastapi import FastAPI

app = FastAPI(docs_url="/documentation", redoc_url="/redo")


@app.get("/items/")
async def read_items():
    return [{"name": "Foo"}]

 

访问 Swagger API 文档

 

posted @ 2021-09-26 23:07  小菠萝测试笔记  阅读(914)  评论(0编辑  收藏  举报