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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)