Move Flask-Restplus Swagger API Docs

浪尽此生 提交于 2019-12-06 00:37:21

With Flask-Restplus <= 0.8.0 you should write:

from flask import Flask
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)
api = Api(app, ui=False)

@app.route('/doc/', endpoint='doc')
def swagger_ui():
    return apidoc.ui_for(api)

Note the use of a @app instead of @api

Starting from v0.8.1 (soon to be released), you will simply have to write:

from flask import Flask
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)
api = Api(app, doc='/doc/')

See: http://flask-restplus.readthedocs.org/en/latest/swagger.html#swagger-ui

After recently struggling with this myself, I've had luck with this approach:

from flask import Flask, Blueprint
from flask.ext.restplus import Api, apidoc

app = Flask(__name__)

blueprint = Blueprint('api', __name__)
api = Api(blueprint, ui=False)

@blueprint.route('/doc/', endpoint='doc')
def swagger_ui():
   return apidoc.ui_for(api)

app.register_blueprint(blueprint)

It looks like @api will need Resource, so I modified the code a bit to get around the error. The following will work only at /doc/, not the default root level.

from flask import Flask, make_response
from flask.ext.restplus import Api, apidoc, Resource

app = Flask(__name__)
api = Api(app, ui=False)

@api.route('/doc/', endpoint='doc', doc=False)
class ApiDoc(Resource):
    def get(self):
        return make_response(apidoc.ui_for(api))

app.register_blueprint(apidoc.apidoc)

if __name__ == '__main__':
    app.run(debug=True)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!