Chris Chris - 1 year ago 130
Python Question

Flask-Restful ignores blueprint's url_prefix

I want to use Flask blueprints to organize my Flask-Restful resources into separate url prefixes. Regardless of what url prefix I set (during either blueprint creation or registration), everything gets mapped to the raw route paths. How do I correctly use Restful with blueprints?

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

api.add_resource(Building, '/<int:id>', endpoint='building')
api.add_resource(Jack, '/<int:id>', endpoint='jack')

building_api = Blueprint('building_api', __name__)
jack_api = Blueprint('jack_api', __name__)

app.register_blueprint(building_api, url_prefix='/buildings')
app.register_blueprint(jack_api, url_prefix='/jacks')

All documentation I can find says that these should now be available at
, but both of those urls 404 and instead I can access the building one at
. Hard coding the path in
fixes it, but defeats the point of

Answer Source

You need to pass the blueprint to the Api instance, not the app.

building_bp = Blueprint('buildings', __name__)
building_api = Api(building_bp)
building_api.add_resource(Building, '/<int:id>')
app.register_blueprint(building_bp, url_prefix='/buildings')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download