how to flask get json data from post request in pytho

Published on Aug. 22, 2023, 12:16 p.m.

To get JSON data from a POST request in Flask, you can use the request module. Here’s an example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/post_json', methods=['POST'])
def post_json():
    data = request.get_json()
    # do something with the data
    return 'Received JSON data'

if __name__ == '__main__':
    app.run()

In this example, the post_json function is a route for a POST request to the /post_json URL. Inside the function, the request.get_json() method is used to parse the request data and return a JSON object. You can then use the data object to access the request data and do any processing you need to. Finally, the function returns a response string indicating that it received the JSON data.

Note that you can also use the .json property of the request object to get the JSON data, like this: data = request.json. Either method should work equally well.

Tags: