API in Flask--returns JSON but HTML exceptions break my JSON client API in Flask--returns JSON but HTML exceptions break my JSON client flask flask

API in Flask--returns JSON but HTML exceptions break my JSON client


You should define HTTP error handlers in flask.

A simple JSON returing 404 handler might look something like this:

@app.errorhandler(404)def page_not_found(e):    return flask.jsonify(error=404, text=str(e)), 404

With this you will be able to check for data.error on the client and if it exists you can get the error text with data.text (the error passed as e is werkzeug.exceptions.NotFound whose string representation is "404: Not Found").


Making the traceback available to the JSON client has the potential to disclose sensitive information.

My advice is:

  • turn debug off
  • install a log aggregation tool like sentry
  • make the error 500 page for this application return a generic error in json format

The 500 page could look like:

{ "error": "500 - internal server error" }


The code below should do the trick. So the idea is to catch any exception that might have been raised, get the exception details formatted as a string using the traceback module and then return that as valid json. I would recommend putting a bunch of except statements with the main types of errors you expect to happen and a more readable error message. Then you can have one last except as a catch all in case something strange and unexpected happens.

import traceback@app.route('/route1')def api_route1():    if user_id in request.args:         try:            k1 = request.args['user_id']            return flask.jsonify(recs=some_function(k1))        except:            return flask.jsonify(exception=traceback.format_exc())    else:        return flask.jsonify(exception="no valid user_id supplied")