Flask abort with json example


In this short tutorial we show an example on how to return a json when using flask.abort:

from flask import abort, jsonify
abort(jsonify(message="Message goes here"), 400)

In the previous example we are using jsonify with the message and then the abort status code.

Alternative using handlers

You could set a handler for all error of a particular status code:

    def unauthorized(error):
        response = make_response(jsonify({'code': 401, 'message': 'You are not authorized to access'}), 401)
        return response

In this example you have registered in yout flask app that the error handler for the status code 401 will return a json with the message "You are not authorized to access". You can also use the parameter error to improve the error message, but be careful since some information leak could be shown.