Search code examples
pythonflaskflask-restful

How to use url_map.iter_rules with blueprint object instead of app


I have a blueprint object "api" and a apis.py file where I have many APIs defined with api.route annotation. eg:

@api.route('/', methods=['GET'])
def get_info():

I want to iterate and get summary of all the APIs I have same as what we get when we use "url_map.iter_rules" on app object. How can we do this using api blueprint object? I have registered the blueprint in my init.py file using

from .api_1 import api as api_blueprint
app.register_blueprint(api_blueprint)

Solution

  • I think if you call app.url_map.iter_rules() after you've registered the blueprint you'll get all of the endpoints of the subdomains too, e.g.

    api.py

    from flask import Blueprint
    api = Blueprint('api', __name__)
    @api.route('/')
    def call_api():
            return ""
    

    init.py:

    from flask import Flask, Blueprint
    from api import api
    
    public = Blueprint('public', __name__)
    @public.route('/')
    def home():
            return render_template('public/home.html')
    
    
    app = Flask(__name__)
    app.register_blueprint(public)
    app.register_blueprint(api, subdomain='api')
    print(list(app.url_map.iter_rules()))
    
    [<Rule 'api|/' (GET, HEAD, OPTIONS) -> api.call_api>,
     <Rule '/' (GET, HEAD, OPTIONS) -> public.home>,
     <Rule '/static/<filename>' (GET, HEAD, OPTIONS) -> static>]