Flask Essentials – Handling 400 and 404 requests in Flask REST API

- - Python, Tutorials

Flask is a microframework for Python based on Werkzeug, Jinja 2. Flask is simple and straightforward. However less has been discussed in terms of handling non-existent resource request on the Flask API. Since we are talking to and fro using AJAX and what not, it is highly important for the client to consume a proper acknowledgement of some sort in cases of failure. It is this very small implementation that does the work for us however we seem to never bring this up on online content.

Flask provides a mechanism through errorhandler decorator to implement a custom error handling based on the error status code. These errors are generally termed as route errors. Below is a sample implementation of the 400 and 404 errors on the Flask API.

@APP.errorhandler(400)
def not_found(error):
    """
    Gives error message when any bad requests are made.
    Args:
        error (string):
    Returns:
        Error message.
    """
    print error
    return make_response(jsonify({'error': 'Bad request'}), 400)
@APP.errorhandler(404)
def not_found(error):
    """
    Gives error message when any invalid url are requested.
    Args:
        error (string): 
    Returns:
        Error message.
    """
    print error
    return make_response(jsonify({'error': 'Not found'}), 404)

Similarly, you can handle application errors too. However, it is important to note that the application errors arise due to code blocks on the server and hence appropriate handling is essential. I might as well do a follow up on this post for application error handling with appropriate logging.

A one man army producing contents and maintaining this blog. I am a hobbyist programmer and enjoy writing scripts for automation. If you'd like a process to be automated through programming, I also sell my services at Fiverr You can always communicate your thoughts/wishes/questions to me at bbhishan@gmail.com

There Are 1 Comment On This Article.

Leave a Reply

Your email address will not be published. Required fields are marked *