如何为 FastAPI 生成 swagger 2.0 文档

Asd*_*dfg 5 python swagger fastapi

我正在使用 FastAPI 开发微服务并将其部署到 Cloud Run。我在API网关前面添加API网关。创建 API Gateway 时,它要求我上传 API Spec 文件。因为我使用的是 FastAPI,所以生成的文档适用于 3.0.2。

我尝试覆盖custom_openapi定义并提供,openapi_version但它不起作用,并且我收到一条错误消息

无法呈现此定义 提供的定义未指定有效的版本字段。

请指明有效的 Swagger 或 OpenAPI 版本字段。支持的版本字段包括 swagger: "2.0" 和那些匹配 openapi: 3.0.n 的字段(例如 openapi: 3.0.0)。

这就是我的custom_openapi定义:

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom title",
        version="2.5.0",
        description="This is a very custom OpenAPI schema",
        routes=app.routes,
        openapi_version="swagger:2.0" # I have tried 2.0

    )
Run Code Online (Sandbox Code Playgroud)

有没有办法为我的 FastAPI 生成 Swagger 2.0 文档?

小智 0

您可以使用FastAPI生成OpenAPI 3.0。

并使用这个https://www.npmjs.com/package/api-spec-converter将其转换为 Swagger 2.0

警告:它适用于 fastapi==0.98.0 自 fastapi 0.99 切换到 OpenAPI 3.1 以来,它不再工作(https://fastapi.tiangolo.com/release-notes/#0990

您需要将此代码添加到您的应用程序中:

@app.get("/openapi_v2")
async def openapi_v2():
    schema = app.openapi()
    schema.update(
        host="your.app.com",
        schemes=["https"],
        produces=["application/json"],
    )

    if len(schema["paths"]) == 0:
        return schema

    endpoint = list(schema["paths"].keys())[0]
    schema["paths"]["/"] = schema["paths"][endpoint]
    del schema["paths"][endpoint]

    for endpoint in schema["paths"].keys():
        for method in schema["paths"][endpoint].keys():
            if "tags" in schema["paths"][endpoint][method]:
                del schema["paths"][endpoint][method]["tags"]

            schema["paths"][endpoint][method]["x-google-backend"] = {
                "address": "https://your.app.com",
                "path_translation": "APPEND_PATH_TO_ADDRESS",
                "protocol": "h2",
            }

    return schema
Run Code Online (Sandbox Code Playgroud)

那么这应该可以完成工作:

api-spec-converter --from=openapi_3 --to=swagger_2 http://localhost:5000/openapi_v2
Run Code Online (Sandbox Code Playgroud)