Skip to main content
 首页 » 编程设计

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

2024年12月31日9qlqwjy

我在 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)  

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

请您参考如下方法:

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

flask-restplus 源代码中的 Swagger 类是 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 

我可能错了,但源代码表明 API 文档仅作为 JSON 返回,可在 http://localhost:5000/swagger.json 获得默认。我找不到 YAML 的任何内容。

但是有一个解决方法可以为您的 API 生成 YAML 文档。我使用 json 和 yaml 库将来自 /swagger.json 的 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)  

希望对您有所帮助。