Complete the code to return a JSON response using Flask.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def home(): return [1]({'message': 'Hello, world!'})
json instead of jsonify causes errors.render_template returns HTML, not JSON.The jsonify function formats the dictionary as a JSON response in Flask.
Complete the code to set the HTTP status code to 201 in the JSON response.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/create') def create(): return jsonify({'result': 'Created'}), [1]
Status code 201 means the resource was successfully created.
Fix the error in returning a JSON response with a custom header.
from flask import Flask, jsonify, make_response app = Flask(__name__) @app.route('/custom') def custom(): response = make_response(jsonify({'status': 'ok'})) response.headers['X-Custom-Header'] = [1] return response
Header values must be strings, so use quotes around the value.
Fill both blanks to return a JSON response with a 404 status and a custom error message.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/notfound') def not_found(): return jsonify({'error': [1]), [2]
The JSON error message is a string, and the status code 404 means not found.
Fill all three blanks to create a JSON response with a nested dictionary, a 202 status code, and a custom header.
from flask import Flask, jsonify, make_response app = Flask(__name__) @app.route('/process') def process(): data = {'task': [1], 'status': 'processing'} response = make_response(jsonify(data), [2]) response.headers['X-Task-ID'] = [3] return response
The task name is a string, status code 202 means accepted, and the header value is a string ID.