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.
JSON request parsing in 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.
data = request.get_json()
data = request.get_json(force=True)data = request.get_json(silent=True)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.
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)
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.
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.
Practice
Solution
Step 1: Understand Flask request object
The Flaskrequestobject provides methods to access incoming request data.Step 2: Identify JSON parsing method
The methodget_json()is designed to parse JSON data from the request body safely.Final Answer:
request.get_json() -> Option DQuick Check:
JSON parsing method = request.get_json() [OK]
- Using request.json() which is not a method
- Trying to parse JSON from request.data directly
- Using non-existent methods like parse_json()
Solution
Step 1: Check import and usage
Correct usage importsrequestfromflaskand callsrequest.get_json()as a method.Step 2: Identify correct method call
from flask import request @app.route('/data') def data(): data = request.get_json() return data correctly callsrequest.get_json()with parentheses to parse JSON.Final Answer:
Option A code snippet -> Option AQuick Check:
Correct import and method call = from flask import request @app.route('/data') def data(): data = request.get_json() return data [OK]
- Calling get_json without parentheses
- Using request.json() which does not exist
- Accessing request.json property which is not standard
from flask import Flask, request
app = Flask(__name__)
@app.route('/user', methods=['POST'])
def user():
data = request.get_json()
return f"Hello, {data['name']}!"
Solution
Step 1: Parse JSON from request
The client sends valid JSON with key "name" and value "Alice".request.get_json()parses it into a Python dict.Step 2: Access dictionary key and return string
The code accessesdata['name']which exists, so it returns the formatted string "Hello, Alice!".Final Answer:
"Hello, Alice!" -> Option AQuick Check:
Valid JSON with 'name' key = "Hello, Alice!" [OK]
- Assuming get_json() returns None if JSON is missing
- Not handling missing keys causing KeyError
- Confusing get_json() with request.data string
@app.route('/submit', methods=['POST'])
def submit():
data = request.get_json()
return data['email']
Solution
Step 1: Analyze JSON key access
The code accessesdata['email']without checking if 'email' exists in the JSON data.Step 2: Identify potential error
If the client sends JSON without 'email', this causes a KeyError and crashes the route.Final Answer:
It may raise a KeyError if 'email' is missing in JSON -> Option BQuick Check:
Missing key access causes KeyError = It may raise a KeyError if 'email' is missing in JSON [OK]
- Assuming get_json() always returns dict with all keys
- Not handling missing or invalid JSON gracefully
- Confusing method errors with key errors
@app.route('/info', methods=['POST'])
def info():
data = request.get_json()
return data['id']
Solution
Step 1: Use silent=True to avoid exceptions
Callingrequest.get_json(silent=True)returns None instead of raising an error if JSON is missing or invalid.Step 2: Check if data is None before accessing keys
Before accessingdata['id'], check ifdatais not None to avoid crashes.Final Answer:
Use data = request.get_json(silent=True) and check for None -> Option CQuick Check:
Silent parsing + None check = safe JSON access [OK]
- Using request.json() which is not a method
- Not checking if data is None before key access
- Using force=True which may cause errors if content is not JSON
Ready to prove it?
Pass the test and this pattern moves unknown
