Skip to content

Instantly share code, notes, and snippets.

@techiev2
Last active June 28, 2021 18:17
Show Gist options
  • Save techiev2/cee6d6506954b02d3e71f92f2f682527 to your computer and use it in GitHub Desktop.
Save techiev2/cee6d6506954b02d3e71f92f2f682527 to your computer and use it in GitHub Desktop.
Simple route to expose all of an API's routes and basic information in a Flask app
import inspect
def is_json_responder(responder_fn):
"""Helper function to check if a function is a JSON responder. Uses
inspect to get the source code and identifies the last line being a
jsonify call
"""
lines = [_ for _ in inspect.getsource(responder_fn).split("\n") if _]
return "jsonify({" in lines[-1]
@APP.route("/")
@cross_origin()
def root_view():
"""
API route handler for root. Returns a list of application routes
for DevX. Skips "/" and "/static". Uses a inspect based helper to isolate only
methods that respond with a jsonify call
"""
_globals = globals()
skip_methods = ("HEAD", "OPTIONS")
response = {}
app_root = "http://{host}:{port}".format(**CONFIG.get("app"))
for item in APP.url_map.iter_rules():
if item.rule == "/" or "static" in item.rule:
continue
handler = _globals.get(item.endpoint)
if not is_json_responder(handler):
continue
response.update({
item.endpoint: {
"description": handler.__doc__,
"methods": ", ".join((_ for _ in item.methods if _ not in skip_methods)),
"uri": "{}{}".format(app_root, item.rule)
}
})
return jsonify(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment