Search code examples
pythonrestflaskflask-restful

Implementing API exception flask-restful


I am trying to catch the Exception which is raised when the url provided is a messy and wrong url and then return the error response as JSON. This is what i did to implement this logic.

The exception is raised inside the Analysis class when the key_id is not a valid key for S3.

def url_error(status_code, message, reason):
    response = jsonify({
        'status': status_code,
        'message': message,
        'reason': reason
    })
    response.status_code = status_code
    return response


class RowColumnCount(Resource):
    def get(self, key_id):
        try:
            rc = Analysis(key_id=key_id)
        except S3ResponseError as e:
            return url_error(e.status, e.message, e.reason)
        json_response = json.loads(rc.count_rows_columns())
        return json_response

The above code works fine but its kinda getting repetitive for 50 different Resource classes. Each Resource class should handle this specific error. How to make it a decorator, such that code repetitiveness is reduced.

I am using Flask, Flask-Restful, Python 3.4.3


Solution

  • There are a couple of ways you can achieve what you're trying to do but I think the cleanest way is to extend the Resource class as described in the Flask-Restful docs here and create a new decorator whose job is to catch the S3ResponseError and return the appropriate response. You can then subclass all your resources from your new base Resource class.

    Also I would suggest you specify an API level json_output method as described here and here so that way all you have to do is return a dict from any of your resources and they'll be converted to JSON appropriately.