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

Rik*_*iko 4 python swagger swagger-ui flask-restplus

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

from flask import Flask
from flask_restplus import Resource, Api

app = Flask(__name__)                  #  Create a Flask WSGI application
api = Api(app)                         #  Create a Flask-RESTPlus API

@api.route('/hello')                   #  Create a URL route to this resource
class HelloWorld(Resource):            #  Create a RESTful resource
    def get(self):                     #  Create GET endpoint
        return {'hello': 'world'}

if __name__ == '__main__':
    app.run(debug=True) 
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中导航到时,loacalhost:5000/我得到了基本的 Swagger 文档,但我找不到在哪里可以获得 API 的机器可读的纯 yaml 表示形式,它不应该自动生成吗?

ama*_*anb 6

我在官方Flask-restplus 文档中找不到有关“Swagger Yaml 文档生成”的任何信息。因此,我决定检查源代码,发现该类Swagger实现了 API 实例的 Swagger 文档生成。

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

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
Run Code Online (Sandbox Code Playgroud)

我可能是错的,但源代码表明 API 文档仅按默认情况下JSON可用的方式返回http://localhost:5000/swagger.json。我找不到 YAML 的任何内容。

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

from flask import Flask
from flask_restplus import Resource, Api
from flask_restplus.api import Swagger
import requests
import json, yaml

app = Flask(__name__)                  #  Create a Flask WSGI application
api = Api(app)                         #  Create a Flask-RESTPlus API

@api.route('/hello')                   #  Create a URL route to this resource
class HelloWorld(Resource):            #  Create a RESTful resource
    def get(self):                  
        return {'hello': 'world'}

@api.route('/swagger.yml')
class HelloWorld(Resource):    
    def get(self):
       url = 'http://localhost:5000/swagger.json'       
       resp = requests.get(url)
       data = json.loads(resp.content)    
       with open('yamldoc.yml', 'w') as yamlf:
           yaml.dump(data, yamlf, allow_unicode=True)
       return {"message":"Yaml document generated!"}


if __name__ == '__main__':
    app.run(debug=True) 
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。