BudiBadu Logo
Samplebadu

Flask by Example: Request JSON Payload

Flask 3.0+

Modern single-page applications (SPAs) and mobile apps often communicate via JSON APIs. Flask provides built-in support for parsing JSON request bodies.

Code

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/api/user', methods=['POST'])
def create_user():
    # 1. Check Content-Type header
    if not request.is_json:
        return jsonify({"error": "Missing JSON in request"}), 400

    # 2. Parse JSON body
    # get_json() returns a Python dictionary (or list)
    # Returns None if parsing fails (unless silent=True)
    data = request.get_json()
    
    name = data.get('name')
    email = data.get('email')
    
    # 3. Validate data
    if not name or not email:
        return jsonify({"error": "Name and email required"}), 422
        
    # 4. Return JSON response
    return jsonify({
        "status": "success",
        "user_id": 123,
        "message": f"User {name} created"
    }), 201

Explanation

Flask's request.get_json() method is the standard way to parse incoming JSON request bodies. It automatically decodes the JSON data into Python dictionaries or lists, making it easy to work with API payloads.

The method strictly checks the Content-Type header to ensure it matches application/json. If the header is missing or incorrect, or if the JSON is malformed, Flask will return a 400 Bad Request error, protecting your application from invalid input.

For responses, the jsonify() function is a helper that serializes your Python dictionary into a JSON string. It also sets the correct Content-Type: application/json header on the response, ensuring the client interprets the data correctly as JSON.

Code Breakdown

8
request.is_json is a boolean property that checks if the mimetype indicates JSON (e.g., application/json). It's a quick way to validate the request format before attempting to parse it.
14
request.get_json() parses the body. If the JSON is malformed, Flask will automatically raise a 400 Bad Request error, aborting the request. You don't need a try/except block for basic syntax errors.
21
Returning 422 Unprocessable Entity is semantically more correct than 400 when the syntax is valid (it's valid JSON) but the semantic content (missing fields) is invalid.
24
jsonify() creates a Response object. It is equivalent to Response(json.dumps(data), mimetype='application/json').