Rectangle 27 0

python How can I return a common JSON object in my flask API?


@app.route('/api/blah/')
 def my_route():
     results = calculate_my_results()
     return jsonify(format_api_result(results))

 def format_api_result(data):
     # add in your extra metadata here, return a dictionary

A function seems to me to be the most straightforward and most flexible way to do what you want. It's a little extra code, but so's a decorator. And while you can certainly do this in a decorator, I don't think it adds much here except complexity.

If you do want to go the decorator route, check out this:

What about just writing a wrapper function? I would probably do something like:

for a good explanation of how decorators work and how you control exactly when the wrapped function gets called.

Note