0

I am developing a REST API with python and flask, I leave the project here Github project

I added error handlers to the application but when I run an abort function, it gives me a default message from Flask, not the structure I am defining.

I will leave the path to the handlers and where I run the abort from. Handlers abort(400)

Flask message

  • This question seems similar to what you are facing and might point you in the right direction - https://stackoverflow.com/questions/40510056/flask-restful-not-found-handling-for-blueprint – DMcP89 Dec 02 '22 at 05:16
  • Thanks for the reference @DMcP89, I will try it and if it works I will add it as an answer. – Jean Piffaut Dec 02 '22 at 14:35

1 Answers1

0

Ok, the solution was told to me that it could be in another question.

What to do is to overwrite the handler function of the Flask Api object.

With that, you can configure the format with which each query will be answered, even the ones that contain an error.

def response_structure(code_status: int, response=None, message=None):
    if code_status == 200 or code_status == 201:
        status = 'Success'
    else:
        status = 'Error'

    args = dict()
    args['status'] = status
    if message is not None:
        args['message'] = message

    if response is not None:
        args['response'] = response

    return args, code_status


class ExtendAPI(Api):

    def handle_error(self, e):
        return response_structure(e.code, str(e))

Once the function is overwritten, you must use this new one to create

users_bp = Blueprint('users', __name__)
api = ExtendAPI(users_bp)

With this, we can then use the flask functions to respond with the structure that we define.

if request.args.get('name') is None:
    abort(400)

Response JSON

{
    "response": "400 Bad Request: The browser (or proxy) sent a request that this server could not understand.",
    "status": "Error"
}