0
0
Flaskframework~5 mins

JSON request parsing in Flask

Choose your learning style9 modes available
Introduction

We use JSON request parsing to read data sent by users in a simple, organized way. It helps our app understand what the user wants.

When a user sends data from a web form using JavaScript in JSON format.
When building an API that accepts data from other apps or devices.
When you want to get information like user name or choices from a mobile app.
When you need to handle data sent by a client without using HTML forms.
Syntax
Flask
from flask import request

@app.route('/example', methods=['POST'])
def example():
    data = request.get_json()
    # use data dictionary here
    return 'OK'

request.get_json() reads the JSON data sent in the request body and converts it into a Python dictionary.

Make sure the client sends the header Content-Type: application/json so Flask knows to parse JSON.

Examples
Basic way to get JSON data as a Python dictionary.
Flask
data = request.get_json()
Force parsing JSON even if the content type header is missing or incorrect.
Flask
data = request.get_json(force=True)
Returns None instead of raising an error if JSON is invalid or missing.
Flask
data = request.get_json(silent=True)
Sample Program

This Flask app has a route '/greet' that accepts POST requests with JSON data. It reads the 'name' from the JSON and returns a greeting message in JSON format.

Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/greet', methods=['POST'])
def greet():
    data = request.get_json()
    name = data.get('name', 'Guest')
    message = f"Hello, {name}!"
    return jsonify({'message': message})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always check if request.get_json() returns None to avoid errors if no JSON is sent.

Use jsonify() to send JSON responses back to the client properly.

Summary

Use request.get_json() to read JSON data sent by clients.

Clients must send JSON with the correct content type header.

Handle missing or invalid JSON gracefully to avoid crashes.