Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot return 404 error as json instead of html from a Flask-Restful app

I am working on a simple Flask REST API test and when I call the {{url}}/items for example I get the items list. However if a call is passed to an endpoint that does not exist for example {{url}}/itemsss then I get the error 404 in html.

I would like to make the error handling more friendly and return json instead of html for certain errors such as 400, 404,405...

For the 404 for example i tried this:

@app.errorhandler(404)
def not_found(e):
    response = jsonify({'status': 404,'error': 'not found',
                        'message': 'invalid resource URI'})
    response.status_code = 404
    return response

However it does not work.

My issue is similar to this one: Python Flask - Both json and html 404 error

I wanted to know, if using the blueprints the only way to accomplish this?

If there a simpler way to output the 404 error as json?

For example instead of this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>404 Not Found</title>

<h1>Not Found</h1>

<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>

Something like this:

{

error: true,

status: 404,

code: "error.notFound",

message: "API endpoint not found",

data: { }

}

I appreciate your help with this.

like image 573
Kintaro Avatar asked Mar 09 '19 20:03

Kintaro


People also ask

How do I return a JSON error in Flask?

To do so we can use the make_response() function in Flask. We still make use of jsonify() in combination with this make_response() so that the error message is a correct JSON string.

Does Flask return JSON?

jsonify() is a helper method provided by Flask to properly return JSON data.

What is Flask_restful?

Flask-RESTful¶ Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs. It is a lightweight abstraction that works with your existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup. If you are familiar with Flask, Flask-RESTful should be easy to pick up.


1 Answers

Usually when I need to return a custom error message with Flask-RESTful I would do something like:

from flask import make_response, jsonify

def custom_error(message, status_code): 
    return make_response(jsonify(message), status_code)
like image 182
Miguel Machado Avatar answered Sep 23 '22 14:09

Miguel Machado