Home >Backend Development >Python Tutorial >How to Reliably Retrieve POSTed JSON Data in Flask?

How to Reliably Retrieve POSTed JSON Data in Flask?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 02:45:10516browse

How to Reliably Retrieve POSTed JSON Data in Flask?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn