0
0
Flaskframework~5 mins

JSON response formatting in Flask - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of using jsonify in Flask?
The jsonify function formats Python data structures into a JSON response with the correct content type application/json. It helps send data to the client in a standard JSON format.
Click to reveal answer
beginner
How do you return a JSON response with a custom status code in Flask?
Use jsonify(data), status_code. For example, return jsonify({'message': 'ok'}), 201 sends JSON with HTTP status 201.
Click to reveal answer
beginner
What content type does Flask set automatically when using jsonify?
Flask sets the content type to application/json automatically when you use jsonify. This tells the browser or client that the response is JSON data.
Click to reveal answer
intermediate
Why should you avoid returning a plain Python dictionary directly from a Flask route?
Returning a plain dictionary does not set the content type to JSON automatically. This can cause clients to misinterpret the response. Using jsonify ensures proper JSON formatting and headers.
Click to reveal answer
intermediate
How can you include custom headers in a JSON response in Flask?
Create the response with jsonify, then use response.headers['Header-Name'] = 'value'. Finally, return the response object.
Click to reveal answer
Which Flask function is best for sending JSON responses?
Ajsonify
Brender_template
Credirect
Dsend_file
What content type does jsonify set in the response?
Aapplication/json
Btext/html
Ctext/plain
Dapplication/xml
How do you return a JSON response with status code 404 in Flask?
Areturn render_template('404.html'), 404
Breturn {'error': 'Not found'}, 404
Creturn jsonify({'error': 'Not found'}), 404
Dreturn redirect('/404')
What happens if you return a plain dictionary from a Flask route?
AFlask automatically converts it to JSON
BFlask returns it as plain text without JSON headers
CFlask raises an error
DFlask redirects to another page
How can you add a custom header to a JSON response in Flask?
AAdd header to the dictionary before jsonify
BCustom headers are not allowed in JSON responses
CPass headers as a second argument to jsonify
DUse <code>response.headers['Name'] = 'value'</code> on the response object
Explain how to send a JSON response with a custom HTTP status code in Flask.
Think about how Flask routes return data and status.
You got /3 concepts.
    Describe why using jsonify is better than returning a plain dictionary in Flask routes.
    Consider how browsers and clients understand response data.
    You got /3 concepts.