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
Release: 2024-12-22 02:45:10
Original
515 people have browsed it

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
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template