Return Json Response from Flask View

Return JSON response from Flask view

As of Flask 1.1.0 a view can directly return a Python dict and Flask will call jsonify automatically.

@app.route("/summary")
def summary():
d = make_summary()
return d

If your Flask version is less than 1.1.0 or to return a different JSON-serializable object, import and use jsonify.

from flask import jsonify

@app.route("/summary")
def summary():
d = make_summary()
return jsonify(d)

Sending JSON and status code with a Flask response

Use flask.jsonify(). This method takes any serializable data type. For example I have used a dictionary data in the following example.

from flask import jsonify

@app.route('/login', methods=['POST'])
def login():
data = {'name': 'nabin khadka'}
return jsonify(data)

To return a status code, return a tuple of the response and code:

return jsonify(data), 200

Note that 200 is the default status code, so it's not necessary to specify that code.



UPDATE

As of Flask 1.1, the return statement will automatically jsonify a dictionary in the first return value. You can return the data directly:

return data

You can also return it with a status code:

return data, 200

How to return a json response in one line in flask?

Are you running Flask in debug mode? Try setting JSONIFY_PRETTYPRINT_REGULAR environment variable to false. From the documentation:

The default output omits indents and spaces after separators. In debug mode or if JSONIFY_PRETTYPRINT_REGULAR is True, the output will be formatted to be easier to read.

How can I return a json of files with python flask-restfull?

If I do the same thing with only one file without wrapping the send_file() in {}, I can access that file on the front end with java script.

You mean like:

return send_file('path/to/file.png')

That works, because Flask's send_file function actually returns a Response object.

This is also valid code (as of flask version 1.1.0):

return {"message" : "File not found!"}, 404

Here you're returning a dictionary with the key 'message' and value 'File not found!'. Flask will turn this into a Response object, with a status code of 404.

That dictionary is jsonified automatically (as of flask version 1.1.0).

When you try to return this:

return {"file1" : send_file('uploads/kode.png')}, 200

The Response object returned by send_file is then jsonified, hence the exception:

TypeError: Object of type 'Response' is not JSON serializable


The obvious way to make this work is that the frontend should make a separate request to the server for each image, passing some kind of ID which the Flask route function should then obtain and use to work out the filepath, then ultimately: return sendfile(filepath).

If you really want to send several images in one JSON response, you could look at base64 encoding the image and making a data_uri string which can be JSON serialized. However unless you really need that data to be passed as JSON, the former option is probably the go-to.

Sending JSON response in Flask POST Route

The fetch API in Javascript is nice in the sense that it gives you options you're seeing when you log it like potentially accessing the body as stream (any day now TC 39...), but it's totally over-engineered for the 90% case. The magic incantation to remember is as follows:

New-fangled fancy-pantsed Javascript

// can only do this inside an async function
const resp = await fetch(someURL);
const jsonData = await resp.json();
// step 3, profit

(Very slightly) Old(er) school Javascript

fetch(someURL)
.then(resp => resp.json())
.then(jsonData => /* profit! */);

They are functionally equivalent. Use the newer one if you always wanted to sit at the cool kid's table at lunchtime in school. Use the other if you're a stodgy old curmudgeon like myself who complains about the kids these days with their cool tables and lunchtimes.

view the json in the response of postman

2 options:

  1. Set the the following config value before app.run():

    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
  2. Use return json.dumps(result) instead, but you'll lose the stuff that jsonify does (such as setting return type headers). This can be fixed though by using the code below:
from flask import make_response
import json


class Test(Resource):
def post(self):
data = request.get_json()
response = make_response(json.dumps(data)) # json.dumps has indent=0 by default
response.headers['Content-Type'] = 'application/json; charset=utf-8'
response.headers['mimetype'] = 'application/json'
return response

Please note that there's still a difference between this option and what POSTMAN returns, namely the space after the :

Sidenote, give your app a proper name, instead of app = Flask('') use app = Flask(__name__)



Related Topics



Leave a reply



Submit