Categories
Python Answers

How to get POSTed JSON in Python Flask?

Spread the love

Sometimes, we want to get POSTed JSON in Python Flask.

In this article, we’ll look at how to get POSTed JSON in Python Flask.

How to get POSTed JSON in Python Flask?

To get POSTed JSON in Python Flask, we can use the request.json property.

For instance, we write

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    return jsonify({"uuid":uuid})

if __name__ == '__main__':
    app.run(host= '0.0.0.0',debug=True)

to create the add_message route that gets the JSON payload from request.json.

request.json returns a dictionary.

We make add_message accept POST requests with

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])

Conclusion

To get POSTed JSON in Python Flask, we can use the request.json property.

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 *