python - 如何从现有的 falcon api 生成 Open API 规范?
问题描述
我有一个用 Falcon 框架编写的现有 RESTful API。目前,我将 Sphinx 用于 API 文档。我想切换到 Swagger(现在称为 OpenAPI)并自动生成 Swagger 规范。在GG上搜索了一会,找到了一个PyPi包falcon-swagger-ui。但看起来我必须手动编写规范。我想要像 Sphinx 这样的东西,我可以使用一些 Sphinx 模板编写普通的 python 文档字符串。现在我找到了 p2swagger 但不知道如何设置?谁能建议我该怎么做?预先感谢
解决方案
下面的简短示例(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。它不是完全自动化的,但也许它会为你完成这项工作。
编辑:固定链接
推荐阅读
- hyperledger-fabric - 如何在 Hyperledger Fabric 测试网络中配置 3rd Party CA?
- mysql - MySQL 将 ID 的 JSON_ARRAY 转换为值的 JSON_ARRAY [MySQL 8]
- c++ - 为什么 std::invoke_result_t 为可调用对象提供其他返回类型而不是特征?
- r - 通过tidyverse中的索引将较小的数据帧连接到较大的数据帧?
- audiounit - AUAudioUnit hosting
- c - C中关于内存分配的一些问题
- flutter - NoSuchMethodError:类“FlutterError”没有实例获取器“代码”。接收方:“FlutterError”实例尝试调用:代码)
- c++ - 是否可以从 C++ 中的线程返回退出代码?
- html - 位置粘性无法在 Iphone 上的 Direction RTL 中正常工作
- sharepoint-online - 在 Powershell 中使用 SharePoint PnP 设置文件夹标题