📖 Scenario: You are building a simple web API using Flask. This API will send data back to users in JSON format, which is a common way to share information on the web.
🎯 Goal: Create a Flask app that returns a JSON response using the jsonify function. The response will include a message and a status code.
📋 What You'll Learn
Create a Flask app instance named app
Create a route /hello that returns a JSON response
Use jsonify to send a dictionary with keys message and status
The message value must be "Hello, JSON!"
The status value must be "success"
💡 Why This Matters
🌍 Real World
APIs often send data in JSON format to web or mobile apps. Flask's jsonify makes it easy to send this data correctly.
💼 Career
Knowing how to build JSON APIs with Flask is useful for backend web development jobs and creating services that communicate with frontend apps.
Progress0 / 4 steps
1
Set up Flask app
Import Flask from flask and create a Flask app instance called app.
Flask
Hint
Use app = Flask(__name__) to create the app instance.
2
Import jsonify
Import jsonify from flask to prepare for sending JSON responses.
Flask
Hint
Add jsonify to the import statement from flask.
3
Create route with JSON response
Create a route /hello using @app.route('/hello'). Define a function hello() that returns a JSON response using jsonify with a dictionary containing message set to "Hello, JSON!" and status set to "success".
Flask
Hint
Use @app.route('/hello') above the function and return jsonify with the correct dictionary.
4
Run the Flask app
Add the code to run the Flask app only if the script is run directly. Use if __name__ == '__main__': and call app.run() inside it.
Flask
Hint
Use the standard Python check if __name__ == '__main__': to run app.run().
Practice
(1/5)
1. What does the jsonify function in Flask do?
easy
A. Converts Python data to JSON and sets response headers correctly
B. Converts JSON data to Python objects
C. Creates HTML responses from Python dictionaries
D. Sends plain text responses without headers
Solution
Step 1: Understand the purpose of jsonify
The jsonify function is designed to convert Python data structures like dictionaries or lists into JSON format.
Step 2: Recognize response headers setting
It also automatically sets the HTTP response headers to indicate the content type is JSON, which is important for browsers or clients to understand the data format.
Final Answer:
Converts Python data to JSON and sets response headers correctly -> Option A
Quick Check:
jsonify converts data to JSON with headers [OK]
Hint: jsonify = Python data to JSON response with headers [OK]
Common Mistakes:
Thinking jsonify converts JSON to Python
Assuming jsonify creates HTML
Ignoring response headers setup
2. Which of the following is the correct way to return a JSON response with jsonify in Flask?
easy
A. return jsonify('name', 'Alice', 'age', 30)
B. return json.dumps({'name': 'Alice', 'age': 30})
C. return jsonify({'name': 'Alice', 'age': 30})
D. return jsonify('name': 'Alice', 'age': 30)
Solution
Step 1: Check the syntax for jsonify with a dictionary
The correct syntax is to pass a dictionary inside parentheses: jsonify({'key': value}).
Step 2: Identify the correct option
return jsonify({'name': 'Alice', 'age': 30}) correctly uses a dictionary inside jsonify. return json.dumps({'name': 'Alice', 'age': 30}) uses json.dumps which returns a string, not a Flask response. return jsonify('name': 'Alice', 'age': 30) has incorrect syntax missing braces. return jsonify('name', 'Alice', 'age', 30) passes multiple positional arguments, causing a TypeError.
Final Answer:
return jsonify({'name': 'Alice', 'age': 30}) -> Option C
Quick Check:
jsonify expects a dict inside parentheses [OK]
Hint: Use jsonify with a dictionary inside parentheses [OK]
Common Mistakes:
Using json.dumps instead of jsonify
Passing key-value pairs without braces
Passing multiple positional arguments to jsonify
3. What will be the output content type of this Flask route?
The jsonify function returns a Flask response with the content type set to application/json.
Step 2: Confirm the content type for JSON data
Since the route returns jsonify({'success': True, 'count': 5}), the content type will be application/json.
Final Answer:
application/json -> Option A
Quick Check:
jsonify sets content type to application/json [OK]
Hint: jsonify always sets content type to application/json [OK]
Common Mistakes:
Assuming default is text/html
Confusing with plain text content type
Thinking jsonify returns XML
4. Identify the error in this Flask route using jsonify:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/info')
def info():
data = {'name': 'Bob', 'age': 25}
return jsonify(data['name'], data['age'])
medium
A. Route decorator syntax is wrong
B. Missing parentheses in jsonify call
C. Flask app not initialized correctly
D. jsonify expects a single dictionary or list, not multiple arguments
Solution
Step 1: Analyze the jsonify call arguments
The code calls jsonify(data['name'], data['age']) passing two separate arguments instead of one dictionary or list.
Step 2: Understand jsonify argument requirements
jsonify expects a single argument like a dictionary, list, or keyword arguments, not multiple positional arguments.
Final Answer:
jsonify expects a single dictionary or list, not multiple arguments -> Option D
Quick Check:
jsonify needs one dict/list argument [OK]
Hint: Pass one dict or list to jsonify, not multiple values [OK]
Common Mistakes:
Passing multiple arguments to jsonify
Confusing jsonify with print function
Ignoring argument structure requirements
5. You want to return a JSON response with a list of users and a status message using jsonify. Which code correctly combines a list and a message in the JSON response?
hard
A. return jsonify(['Ann', 'Ben'], status='ok')
B. return jsonify({'users': ['Ann', 'Ben'], 'status': 'ok'})
C. return jsonify(users=['Ann', 'Ben'], 'status': 'ok')
D. return jsonify({'users': ['Ann', 'Ben']}, {'status': 'ok'})
Solution
Step 1: Understand how to combine data in jsonify
To send multiple pieces of data, combine them into a single dictionary with keys and values.
Step 2: Evaluate each option
return jsonify({'users': ['Ann', 'Ben'], 'status': 'ok'}) correctly creates one dictionary with keys 'users' and 'status'. return jsonify(['Ann', 'Ben'], status='ok') passes a list and a keyword argument, which is invalid. return jsonify(users=['Ann', 'Ben'], 'status': 'ok') mixes keyword arguments and dictionary syntax incorrectly. return jsonify({'users': ['Ann', 'Ben']}, {'status': 'ok'}) passes two dictionaries separately, which is not allowed.
Final Answer:
return jsonify({'users': ['Ann', 'Ben'], 'status': 'ok'}) -> Option B
Quick Check:
Combine all data in one dict for jsonify [OK]
Hint: Put all data in one dictionary before jsonify [OK]
Common Mistakes:
Passing multiple arguments instead of one dict
Mixing keyword args and dict syntax wrongly
Trying to jsonify multiple separate dicts
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.