首页 > 解决方案 > 如何从现有的 falcon api 生成 Open API 规范?

问题描述

我有一个用 Falcon 框架编写的现有 RESTful API。目前,我将 Sphinx 用于 API 文档。我想切换到 Swagger(现在称为 OpenAPI)并自动生成 Swagger 规范。在GG上搜索了一会,找到了一个PyPi包falcon-swagger-ui。但看起来我必须手动编写规范。我想要像 Sphinx 这样的东西,我可以使用一些 Sphinx 模板编写普通的 python 文档字符串。现在我找到了 p2swagger 但不知道如何设置?谁能建议我该怎么做?预先感谢

标签: pythonswaggeropenapifalconframeworkopenapi-generator

解决方案


看看falcon-apispec

下面的简短示例(Falcon 快速入门示例的修改版本)应该显示它是如何工作的。

import falcon
from apispec import APISpec
from falcon_apispec import FalconPlugin
import json


class ThingsResource(object):
    def on_get(self, req, resp):
        """Handles GET requests
        ---
        description: Prints cite from Kant
        responses:
            200:
                description: Cite to be returned
        """
        resp.status = falcon.HTTP_200  # This is the default status
        resp.body = ('\nTwo things awe me most, the starry sky '
                     'above me and the moral law within me.\n'
                     '\n'
                     '    ~ Immanuel Kant\n\n')
        resp.content_type = falcon.MEDIA_TEXT


app = application = falcon.API()

things = ThingsResource()
app.add_route("/things", things)

spec = APISpec(
    title="Things APP",
    version="0.0.1",
    openapi_version='3.0',
    plugins=[FalconPlugin(app)],
)

spec.path(resource=things)

print(json.dumps(spec.to_dict))

在使用(例如)gunicorn 运行时,会打印 OpenAPI-Specs。

函数的文档字符串必须以 YAML 格式格式化,因此您仍然需要编写它们。对于更复杂的数据类型,建议使用marshmallow。它不是完全自动化的,但也许它会为你完成这项工作。

编辑:固定链接


推荐阅读