有哪些工具可用于为Flask编写的REST API自动生成文档?

时间:2013-01-12 16:24:49

标签: python rest documentation flask

我正在寻找一种从我编写的Flask REST API自动生成REST API文档的快捷方法。有没有人知道可以做到这一点的工具以及如何标记代码?

3 个答案:

答案 0 :(得分:20)

我建议您Sphinx,将文档添加为__doc__,而Sphinx的autodoc模块将为您生成文档(docs.python.org也使用Sphinx)。标记为reStructuredText,与Markdown类似(如果您更喜欢Markdown,则可以使用pdoc)。

e.g:

@app.route('/download/<int:id>')
def download_id(id):
    '''This downloads a certain image specified by *id*'''
    return ...

答案 1 :(得分:17)

我非常喜欢Swagger因为它允许通过在代码中添加一些装饰器和注释来生成API文档。有一个Flask Swagger可用。

from flask import Flask
from flask.ext.restful import  Api
from flask_restful_swagger import swagger

app = Flask(__name__)
api = swagger.docs(Api(app), apiVersion='1', api_spec_url="/api/v1/spec")

class Unicorn(Resource):
"Describing unicorns"
@swagger.operation(
    notes='some really good notes'
)
def get(self, todo_id):
...

然后你可以通过访问/ api / v1 / spec(它自动提供所需的静态)在html界面中查看你的方法和注释。您也可以使用JSON获取所有API描述并以其他方式解析它。

答案 2 :(得分:6)

有一个Flask扩展名:flask-autodoc用于自动文档,专门解析端点路由规则。您可以添加doc装饰器来指定要进行doc的API:

@app.route('/doc')
@auto.doc()
def documentation():
    '''
    return API documentation page
    '''
    return auto.html()

@app.route('/')
@auto.doc()
def welcome():
    '''
    Welcome API
    '''
    commit_hash = subprocess.check_output(["git", "rev-parse", "HEAD"])
    commit_msg = subprocess.check_output(["git", "log", "-1", "--format=%s"])
    date_time = subprocess.check_output(["git", "log", "-1", "--format=%cd"])
    return "Welcome to VM Service Server. <br/>" \
           "The last commit: %s<br/>Date: %s, <br>Hash: %s" % \
           (commit_msg, date_time, commit_hash), 200

简单的html文档页面如下:

enter image description here