How to Get JSON Data in Flask: Simple Guide
In Flask, you get JSON data from a request using
request.get_json(). This method parses the incoming JSON payload and returns it as a Python dictionary for easy use.Syntax
Use request.get_json() inside a Flask route to access JSON data sent by the client. It returns a Python dictionary if the JSON is valid.
request: Flask object representing the incoming HTTP request.get_json(): Method to parse JSON data from the request body.
python
from flask import Flask, request app = Flask(__name__) @app.route('/json', methods=['POST']) def json_example(): data = request.get_json() return data
Example
This example shows a Flask app with a POST route that receives JSON data and returns it back as a response.
python
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/json', methods=['POST']) def json_example(): data = request.get_json() if not data: return jsonify({'error': 'No JSON received'}), 400 return jsonify({'you_sent': data}) if __name__ == '__main__': app.run(debug=True)
Output
When you send a POST request with JSON {"name": "Alice"} to /json, the response will be {"you_sent": {"name": "Alice"}}
Common Pitfalls
- Not setting
Content-Type: application/jsonheader in the request causesget_json()to returnNone. - Calling
request.jsonwithout checking can raise errors if JSON is invalid. - Using
request.dataorrequest.forminstead ofget_json()for JSON data is incorrect.
python
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/json', methods=['POST']) def wrong_way(): # This will fail if Content-Type is not set or JSON is invalid data = request.json if data is None: return jsonify({'error': 'No JSON or invalid JSON'}), 400 return jsonify(data) @app.route('/json-correct', methods=['POST']) def right_way(): data = request.get_json(force=True, silent=True) if data is None: return jsonify({'error': 'No JSON or invalid JSON'}), 400 return jsonify(data)
Quick Reference
| Method | Description |
|---|---|
| request.get_json() | Parses JSON from request body, returns dict or None if invalid or missing |
| request.json | Shortcut to get JSON, may raise error if JSON invalid |
| request.data | Raw request body bytes, not parsed |
| request.form | Form data, not JSON |
Key Takeaways
Use request.get_json() to safely get JSON data from Flask requests.
Always ensure the client sends Content-Type: application/json header.
Check if get_json() returns None to handle missing or invalid JSON.
Avoid using request.data or request.form for JSON payloads.
Use jsonify() to send JSON responses back to clients.