Categories
Python Answers

How to send JSON and status code with a Python Flask response?

Spread the love

Sometimes, we want to send JSON and status code with a Python Flask response.

In this article, we’ll look at how to send JSON and status code with a Python Flask response.

How to send JSON and status code with a Python Flask response?

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.

For instance, we write

from flask import jsonify

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

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.

Conclusion

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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