Sanic: List of all routes in Sanic, like flask?

Created on 1 Jun 2018  路  2Comments  路  Source: sanic-org/sanic

Is there a way to get a list of all routes and their handlers in Sanic?

Most helpful comment

Hi @garyo

The solution I found once is to lookup into the app.router.routes_names (which is a dictionary containing all the information you may need about your routes).

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route('/hello/<name>')
async def hello(request, name):
    return json({'hello': name})

for handler, (rule, router) in app.router.routes_names.items():
    print(rule)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

Hope, that may help.
Please notice that I got an issue when a / route and a /<name> are defined, the / route will not be printed.

All 2 comments

Hi @garyo

The solution I found once is to lookup into the app.router.routes_names (which is a dictionary containing all the information you may need about your routes).

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route('/hello/<name>')
async def hello(request, name):
    return json({'hello': name})

for handler, (rule, router) in app.router.routes_names.items():
    print(rule)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

Hope, that may help.
Please notice that I got an issue when a / route and a /<name> are defined, the / route will not be printed.

Thanks, that works for me!

Was this page helpful?
0 / 5 - 0 ratings