如何为FastAPI生成Swagger 2.0文档

5
我正在使用FastAPI开发微服务并将其部署到Cloud Run。我在API Gateway前添加了API Gateway。在创建API Gateway时,它要求我上传API规范文件。由于我使用的是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

    )

有没有一种方法可以为我的FastAPI生成Swagger 2.0文档?

4
看起来 FastAPI 不支持 2.0,只支持 3.0 版本:https://github.com/tiangolo/fastapi/issues/70。 - Bao Huynh Lam
顺便问一下,将文档从API Gateway提供而不是从FastAPI提供有什么优势? - ron rothman
@ronrothman 我觉得他没有从API Gateway提供文档。这个网关不支持OpenAPI v.3,而是需要版本2。就是这样。 - Alexander Goida
1个回答

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

如果是这样的话,这应该能胜任工作。
api-spec-converter --from=openapi_3 --to=swagger_2 http://localhost:5000/openapi_v2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接