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:
@app.errorhandler(401)
def unauthorized(error):
response = jsonify({'code': 401, 'message': 'You are not authorized to access'})
response.status_code = 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.