pythonflaskerror-handlingcustom-error-handling

customizing flask error handlers for json returning api


I have a flask app which has two types of routes :

(1). routes for website, like /home, /user/, /news_feed

(2). json returning apis for mobile app, like /api/user, /api/weather etc.

I am using custom error pages for common errors like 404 and 500 via @app.errorhandler decorator provided by flask - for my website

@app_instance.errorhandler(404)
def page_note_found_error(err):
  return render_template("err_404.html"), 404

@app_instance.errorhandler(500)
def internal_server_error(err):
  db_instance.session.rollback()
  return render_template("err_500.html"), 500

I do not want my mobile apis to return these error pages if say i get a 500 error via the mobile api.

Is there a way to bypass or customize the error handler for some routes(api) so that it returns json response instead of my custom error pages


Solution

  • You can dig into the details of the request to determine the URL path. If the path is prefixed by /api/ then you can treat it as an API request and return a JSON response.

    from flask import request, jsonify
    
    API_PATH_PREFIX = '/api/'
    
    @app_instance.errorhandler(404)
    def page_not_found_error(error):
        if request.path.startswith(API_PATH_PREFIX):
            return jsonify({'error': True, 'msg': 'API endpoint {!r} does not exist on this server'.format(request.path)}), error.code
        return render_template('err_{}.html'.format(error.code)), error.code
    

    This is not ideal. I thought that you might have been able to handle this with Flask blueprints, but the blueprint specific error handler does not work for 404, instead the app level handler is invoked.