0
0
Flaskframework~5 mins

JSON responses with jsonify in Flask - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of jsonify in Flask?

jsonify converts Python data structures like dictionaries or lists into a JSON response Flask can send to the client. It also sets the correct content type application/json.

Click to reveal answer
beginner
How do you return a JSON response with a status code using jsonify?

Return a tuple: return jsonify(data), status_code. For example, return jsonify({'message': 'ok'}), 200 sends JSON with HTTP status 200.

Click to reveal answer
beginner
True or False: jsonify automatically sets the Content-Type header to application/json.

True. This helps browsers and clients understand the response is JSON data.

Click to reveal answer
intermediate
What happens if you try to jsonify a Python object that is not JSON serializable?

Flask raises a TypeError because it cannot convert the object to JSON. You must convert or simplify the object first.

Click to reveal answer
intermediate
Why is it better to use jsonify instead of json.dumps in Flask responses?

jsonify sets the correct headers and returns a Flask Response object directly. json.dumps only creates a JSON string, so you must manually set headers and response type.

Click to reveal answer
What does jsonify do in Flask?
ACreates HTML responses
BConverts JSON to Python objects
CConverts Python data to JSON and sets response headers
DStarts the Flask server
How do you send a JSON response with status 404 using jsonify?
Areturn jsonify({'error': 'Not found'})
Breturn jsonify(404, {'error': 'Not found'})
Creturn 404, jsonify({'error': 'Not found'})
Dreturn jsonify({'error': 'Not found'}), 404
Which header does jsonify set automatically?
AContent-Type: text/html
BContent-Type: application/json
CAuthorization
DCache-Control
What error occurs if you try to jsonify a non-serializable object?
ATypeError
BValueError
CKeyError
DImportError
Why prefer jsonify over json.dumps in Flask?
A<code>jsonify</code> sets headers and returns a response object
B<code>json.dumps</code> is faster
C<code>json.dumps</code> sets headers automatically
DThey are the same
Explain how to create and return a JSON response in Flask using jsonify.
Think about how Flask sends data to the browser in JSON format.
You got /4 concepts.
    Describe what happens if you try to jsonify a Python object that Flask cannot convert to JSON.
    Consider what JSON can represent and what Python objects might not fit.
    You got /3 concepts.