Search code examples
resturlhttp-methodflask

methods(http verbs) of all endpoints in current flask blueprint


I'm trying to generate the related links for each RESTful API endpoint not just the current request. Another way which would also be acceptable, is that I want to generate all the endpoints of the current blueprint (in this case called 'blueprint_name'). Here is the abstract of my current setup:

def function_that_generates_links():
   #what should I put here?

blueprint_name = Blueprint('blueprint_name', __name__, url_prefix='/blueprint_name')

@blueprint_name.route('/', methods=['GET'])
def endpoint_name():
   #regular_data_being_sent_out is defined somewhere here
   return jsonify(data=regular_data_being_sent_out,
                  links=function_that_generates_links())

@blueprint_name.route('/other_place', methods=['POST'])
def endpoint_name_other():
   #regular_data_being_sent_out is defined somewhere here
   return jsonify(data=regular_data_being_sent_out,
                  links=function_that_generates_links())
@blueprint_name.route('/another_place', methods=['DELETE'])
def endpoint_name_another_place():
   #regular_data_being_sent_out is defined somewhere here
   return jsonify(data=regular_data_being_sent_out,
                  links=function_that_generates_links())

@blueprint_name.route('/yet_another_place', methods=['PUT'])
def endpoint_name_yet_another_place():
   #regular_data_being_sent_out is defined somewhere here
   return jsonify(data=regular_data_being_sent_out,
                  links=function_that_generates_links())

I want to append to each response emitted by each endpoint the appropriate http 'signatures' of all the other endpoints. In the example code above 'function_that_generates_links()' would be the function to do this. I've already found that url_encode() provides the necessary link I could use, but I also want the appropriate http verb (GET,POST, DELETE...etc). It is finding the corresponding http-verb/method that I'm stuck on. The verb is important because without it the links are incomplete/useless.


Solution

  • You can list all current rules with app.url_map.iter_rules(). Then rule.rule should give you the URI expression and rule.methods a set with the available methods.

    However, AFAIK, you can't do that for a blueprint, or filter by them. The blueprint stores the routes wrapped in lambda functions to be called when registered, and there's no easy way to unwrap that. If you need to go that way, it might be a better idea to subclass Blueprint, redefine the route method and preserve the parameters you want in the Blueprint instance itself.