What is the benefit of using Blueprint in Flask-Restful?

Viewed 1906

I'm new to Flask and the Blueprint concept. I understand the benefit of using Blueprint in a normal Flask application. However, after reading many posts/blogs/documentation, the benefit of using Blueprint with Flask-Restful is still unclear to me.

Let's consider two examples from the Flask-Restful documentation. The first one:

from flask import Flask
from flask_restful import Api
from myapi.resources.foo import Foo
from myapi.resources.bar import Bar
from myapi.resources.baz import Baz

app = Flask(__name__)
api = Api(app)

api.add_resource(Foo, '/Foo', '/Foo/<string:id>')
api.add_resource(Bar, '/Bar', '/Bar/<string:id>')
api.add_resource(Baz, '/Baz', '/Baz/<string:id>')

We have 3 resources. We register them and start the project. Everything is clear at this point. I would be happy with this approach.

Then, they use blueprint:

from flask import Flask, Blueprint
from flask_restful import Api, Resource, url_for

app = Flask(__name__)
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}

api.add_resource(TodoItem, '/todos/<int:id>')
app.register_blueprint(api_bp)

As far as I can see, the code is getting more complicated:

  • More steps required: create the API instance with the blueprint, register the blueprint with the app,...
  • If I have another resource, e.g. user, I have to repeat all of those steps (please correct me if I'm wrong):
user_bp = Blueprint('user', __name__)
user_api = Api(user_bp)
user_api.add_resource(User, '/user/<int:id>')
app.register_blueprint(user_bp)

So, what is the benefit of using Blueprint here?

1 Answers

A blueprint in Flask is an object to structure a Flask application into subsets. This helps in organizing code and separating functionality.

For Flask-RESTful this can be used to create an application subset for your api. So for example you have a core blueprint, an auth blueprint and besides that an api blueprint. It can also be useful when you create a new version of your api that breaks backwards compatibility with the first version. In this case you can create a second blueprint for the new version.

You don’t have to create a new blueprint for each api endpoint that you create, you can reuse the api blueprint for each endpoint like:

from flask import Flask, Blueprint
from flask_restful import Api, Resource, url_for

app = Flask(__name__)
core_bp = Blueprint('core', __name__)
api_bp = Blueprint('api', __name__)
api = Api(api_bp)

@core_bp.route('/')
def index():
    return 'Index'

class TodoItem(Resource):
    def get(self, id):
        return {'task': 'Say "Hello, World!"'}

api.add_resource(TodoItem, '/todos/<int:id>')
api.add_resource(User, '/user/<int:id>')

app.register_blueprint(core_bp)
app.register_blueprint(api_bp, url_prefix='/api')

Like this your core application is accessible via '/' and the api via '/api'.

Related