How to use Flasgger with Flask applications using Blueprints? How to use Flasgger with Flask applications using Blueprints? flask flask

How to use Flasgger with Flask applications using Blueprints?


Now there is an example of blueprint app in https://github.com/rochacbruno/flasgger/blob/master/examples/example_blueprint.py

"""A test to ensure routes from Blueprints are swagged as expected."""from flask import Blueprint, Flask, jsonifyfrom flasgger import Swaggerfrom flasgger.utils import swag_fromapp = Flask(__name__)example_blueprint = Blueprint("example_blueprint", __name__)@example_blueprint.route('/usernames/<username>', methods=['GET', 'POST'])@swag_from('username_specs.yml', methods=['GET'])@swag_from('username_specs.yml', methods=['POST'])def usernames(username):    return jsonify({'username': username})@example_blueprint.route('/usernames2/<username>', methods=['GET', 'POST'])def usernames2(username):    """    This is the summary defined in yaml file    First line is the summary    All following lines until the hyphens is added to description    the format of the first lines until 3 hyphens will be not yaml compliant    but everything below the 3 hyphens should be.    ---    tags:      - users    parameters:      - in: path        name: username        type: string        required: true    responses:      200:        description: A single user item        schema:          id: rec_username          properties:            username:              type: string              description: The name of the user              default: 'steve-harris'    """    return jsonify({'username': username})app.register_blueprint(example_blueprint)swag = Swagger(app)if __name__ == "__main__":    app.run(debug=True)


You just need to add your blueprint's name when you reference endpoint. Blueprints create namespaces. Example below. And useful tip: use app.logger.info(url_for('hello1')) for debugging problems with endpoint - it shows very useful error messages like this Could not build url for endpoint 'hello1'. Did you mean 'api_bp.hello1' instead?.

from flask import Flask, Blueprint, url_forfrom flask_restful import Api, Resourcefrom flasgger import Swagger, swag_fromapp = Flask(__name__)api_blueprint = Blueprint('api_bp', __name__)api = Api(api_blueprint)class Hello(Resource):    @swag_from('hello1.yml', endpoint='api_bp.hello1')    @swag_from('hello2.yml', endpoint='api_bp.hello2')    def get(self, user=''):        name = user or 'stranger'        resp = {'message': 'Hello %s!' % name}        return respapi.add_resource(Hello, '/hello', endpoint='hello1')api.add_resource(Hello, '/hello/<string:user>', endpoint='hello2')app.register_blueprint(api_blueprint)swagger = Swagger(app)app.run(debug=True)


swag_from function have some error to parse file path.you can use doc string to define api in get() first. flasgger will parse MethodView() method like get,post.