How to get POSTed JSON in Flask?

Learn how to use Flask’s request.get_json() to read JSON data from POST requests. Perfect for APIs, webhooks, and client-server communication.

Summarize with AI

Not enough time? get the key points instantly.

When building APIs with Flask, getting JSON data from a client’s POST request is common. Flask makes it easy to extract and work with this data using request.get_json().

Here are the ways to get POSTed JSON data in a Flask route along with some usage tips.

Method 1: Use request.get_json()

Best for: Clean JSON requests with Content-Type: application/json

from flask import Flask, request

app = Flask(__name__)

 

@app.route(‘/data’, methods=[‘POST’])

def get_json():

    data = request.get_json()

    return {‘you_sent’: data}, 200

  • This will automatically parse the incoming JSON.
  • Returns a Python dictionary from the posted JSON body.
  • Returns None if the request body is empty or if the header is not application/json.

Method 2: Use request.json (Shortcut)

Best for: Quick access to JSON when you are sure it’s valid

@app.route(‘/data’, methods=[‘POST’])def get_json_alt():    data = request.json

    return {‘message’: ‘Got it’, ‘data’: data}

  • Same as request.get_json(), but without parameters.
  • Less explicit, so avoid it if you need custom error handling.

Also Read: Top Python Machine Learning Library

Method 3: Handle Fallback with force=True or silent=True

Best for: Handling edge cases with non-standard headers

@app.route(‘/data’, methods=[‘POST’])def get_fallback():

    data = request.get_json(force=True) # Ignores content-type

    return {‘parsed’: data}

  • force=True: Will parse data even if Content-Type is incorrect.
  • silent=True: Will suppress exceptions and return None on error.

Also Read: Return SQL Table as JSON in Python

Tip

Always validate incoming JSON to prevent runtime errors. For safety:

data = request.get_json()if not data or ‘key’ not in data:

    return {‘error’: ‘Missing key’}, 400

Also, make sure your client sends the correct Content-Type header:

Content-Type: application/json

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

How to Copy Files in Python

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…