You want to test a Flask route that returns JSON data. Which code snippet correctly tests the JSON response?
hard📝 Application Q8 of 15
Flask - Testing Flask Applications
You want to test a Flask route that returns JSON data. Which code snippet correctly tests the JSON response?
Aresponse = client.get('/api'); data = response.json()
Bresponse = client.get('/api'); data = response.get_json()
Cresponse = client.get('/api'); data = json.loads(response.data)
Dresponse = client.get('/api'); data = response.data.json()
Step-by-Step Solution
Solution:
Step 1: Recall Flask test client JSON helper
Flask's response object has a method get_json() to parse JSON responses easily.
Step 2: Compare options
response = client.get('/api'); data = response.get_json() uses get_json(), which is the correct and simple way. response = client.get('/api'); data = json.loads(response.data) is close but requires importing json and decoding bytes first.
Final Answer:
response = client.get('/api'); data = response.get_json() -> Option B
Quick Check:
Use response.get_json() to parse JSON [OK]
Quick Trick:Use response.get_json() to get JSON data [OK]
Common Mistakes:
MISTAKES
Using response.json() which does not exist
Trying to call json() on bytes data
Not decoding bytes before json.loads
Master "Testing Flask Applications" in Flask
9 interactive learning modes - each teaches the same concept differently