如何为用flask-restplus编写的现有API生成机器可读的Yaml规范?

时间:2019-01-13 10:56:03

标签: python swagger swagger-ui flask-restplus

我有一个在flask-restplus的帮助下编写的简单API:

loacalhost:5000/

当我在浏览器中导航到{{1}}时,我获得了基本的Swagger文档,但是找不到在哪里可以找到该API的机器可读纯yaml表示形式,是否也应该自动生成?

2 个答案:

答案 0 :(得分:1)

我在官方flask-restplus docs中找不到有关“ Swagger Yaml文档生成”的任何信息。因此,我决定检查源代码,发现dat <- read.table(text = "A A A A A B B B B B 33 45 66 77 88 99 55 66 55 22", header = FALSE, stringsAsFactors = FALSE) row.names(dat) <- c("Client", "Figure") 类为API实例实现了Swagger文档生成。

flask-restplus源代码中的Swagger类是API实例的Swagger文档包装器。此类中的所有方法都建议将API数据序列化为JSON字典。例如,考虑此类的Swagger函数,它将完整的Swagger规范序列化为可序列化的dict。看一下此函数的文档字符串:

as_dict()

我可能是错的,但是源代码表明API文档仅以from flask import Flask from flask_restplus import Resource, Api from flask_restplus.api import Swagger app = Flask(__name__) api = Api(app) swag = Swagger(api) print(swag.as_dict.__doc__) #Output: Output the specification as a serializable ``dict``. :returns: the full Swagger specification in a serializable format :rtype: dict 的形式返回,默认情况下JSON可用。我找不到YAML的任何内容。

但是有一种变通方法可以为您的API生成YAML文档。我使用http://localhost:5000/swagger.jsonjson库将json响应从yaml转储到YAML中,并将其保存到/swagger.json中。您可以通过转到yamldoc.yml来调用它。完整代码:

http://localhost:5000/swagger.yml

我希望这会有所帮助。

答案 1 :(得分:0)

从@amanb答复中,我使我的api返回了yaml文件,而不发出任何请求。 根据flask restplus(或最近的叉子,flask restx)的文档,可以export the Swagger specififcations corresponding to your API使用:

infixr 15 <!==!>

因此,我更喜欢使用def +(other) plus(other) end ,而不是使用from flask import json from myapp import api print(json.dumps(api.__schema__))

由于我的目标是在请求时提供下载文件,因此有必要使用requests的{​​{1}}功能。此外,此文件可以稍后从目录中删除,因此我们可以使用api.__schema__的{​​{1}}装饰器来调用带注释的函数,该函数将删除该文件。完整代码:

send_file
相关问题