Retrieve POSTed JSON Data in Flask
When building Flask APIs, retrieving JSON data from POST requests can be encountered. The following code demonstrates a typical attempt:
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST']) def add_message(uuid): content = request.json print(content) return uuid
However, this method may yield the undesired output of None in the console. To successfully access the posted JSON, it's essential to ensure that the request content type is set to application/json.
The Flask documentation explicitly states that the .json property and .get_json() method require a JSON content type:
"The parsed JSON data if mimetype indicates JSON (application/json, see .is_json)."
To bypass this content type requirement, you can employ the force=True keyword argument to .get_json().
content = request.get_json(force=True)
Note that if an exception arises during this process, it could indicate invalid JSON data. To confirm its validity, it's advisable to use a JSON validator.
The above is the detailed content of How to Reliably Retrieve POSTed JSON Data in Flask?. For more information, please follow other related articles on the PHP Chinese website!