4

I have RESTful routes in a Falcon app defined as below simplified codes. My question is how to get list of all routes with their mapped handlers?

My google search results in little-helpful rpages - one similar issue resolved for Flask app here but no page talking about Falcon.

api = falcon.API(middleware=middleware)
api.add_route('/v1/model_names1', SomeHandlerMappingResource1())
api.add_route('/v1/model_names2', SomeHandlerMappingResource2())

class SomeHandlerMappingResource1:
    def on_get(self, req, resp):
        pass # some biz logic of GET method
    def on_post(self, req, resp):
        pass # some biz logic of POST method
    # etc.

class SomeHandlerMappingResource2:
    pass # similar to handler resource 1 above 
Rajan
  • 1,463
  • 12
  • 26
Nam G VU
  • 33,193
  • 69
  • 233
  • 372

1 Answers1

3

The below code will return a list of tuple with URL and their respective Resources:

def get_all_routes(api):
    routes_list = []

    def get_children(node):
        if len(node.children):
            for child_node in node.children:
                get_children(child_node)
        else:
            routes_list.append((node.uri_template, node.resource))
    [get_children(node) for node in api._router._roots]
    return routes_list

Output

[
    ('/v1/things', <v1.v1_app.ThingsResource object at 0x7f555186de10>), 
    ('/v2/things', <v2.v2_app.ThingsResource object at 0x7f5551871470>), 
    ('/v3/things/{name}', <v3.v3_app.ThingsResource object at 0x7f5551871ba8>)
]

I have read the package and derived this, however, I don't know any builtin method that will return this result.


If you don't like the above function, You can achieve something similar by extending the API class.

I have made a Github repo for versioning the Falcon app, from which you can get an idea of separating the URLs and their relative resources. Github Link

You can have a list of routes and add them by Extended the API class

URLs and Resources will be like:

from v1.v1_app import things

urls = [
    ('/things', things),
]
Rajan
  • 1,463
  • 12
  • 26