Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending JSON and status code with a Flask response [duplicate]

Tags:

json

flask

I know I can set the status code of a response with Response(status=200). How can I return JSON data while setting the status code?

from flask import Flask, Response

@app.route('/login', methods=['POST'])
def login():
    response = Response(status=200)
    # need to set JSON like {'username': 'febin'}
    return response
like image 799
Febin Peter Avatar asked Jul 31 '17 09:07

Febin Peter


People also ask

How do I return status code and JSON in Flask?

To send JSON and status code with a Python Flask response, we can return a tuple with the response body and the status code in our view. to add the login view with the response returned. We return the body with jsonify(data) and we return the status code by putting 200 in the same tuple.

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically.


2 Answers

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
like image 91
Nabin Avatar answered Oct 22 '22 16:10

Nabin


You can append the data to the response like this:

from flask import Flask, json

@app.route('/login', methods=['POST'])
def login():
    data = {"some_key":"some_value"} # Your data in JSON-serializable type
    response = app.response_class(response=json.dumps(data),
                                  status=200,
                                  mimetype='application/json')
    return response

The response data content type is defined by mimetype parameter.

like image 24
Laurynas Tamulevičius Avatar answered Oct 22 '22 17:10

Laurynas Tamulevičius