Last active
June 28, 2021 18:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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