📖 Scenario: You are building a simple web API using Flask. This API will respond to client requests with data and appropriate HTTP status codes to indicate success or errors.
🎯 Goal: Create a Flask API with one route that returns JSON data and uses HTTP status codes to show if the request was successful or if there was an error.
📋 What You'll Learn
Create a Flask app with one route /api/data
Return JSON data with a success message and HTTP status code 200
Add a condition to return an error message with HTTP status code 404 if data is missing
Use Flask's jsonify and make_response to send responses
💡 Why This Matters
🌍 Real World
APIs use HTTP status codes to tell clients if their request worked or if there was a problem. This helps apps communicate clearly over the web.
💼 Career
Knowing how to use HTTP status codes in APIs is essential for backend developers, web developers, and anyone building web services.
Progress0 / 4 steps
1
Set up Flask app and data
Import Flask and jsonify from flask. Create a Flask app called app. Create a dictionary called data with the entry 'message': 'Hello, API!'.
Flask
Hint
Use data = {'message': 'Hello, API!'} exactly to create the data dictionary.
2
Add a config variable for data availability
Create a variable called data_available and set it to True. This will simulate whether the data is available or not.
Flask
Hint
Set data_available = True exactly as shown.
3
Create the API route with status codes
Define a route /api/data using @app.route. Create a function called get_data. Inside it, use an if statement to check if data_available is True. If yes, return jsonify(data) with status code 200. Otherwise, return jsonify({'error': 'Data not found'}) with status code 404. Use make_response to set the status code.
Flask
Hint
Use @app.route('/api/data') and define get_data(). Use make_response with jsonify and status codes 200 or 404.
4
Add the app run command
Add the code to run the Flask app only if the script is run directly. Use if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Hint
Use the standard Flask app run block with debug=True for easy testing.
Practice
(1/5)
1. What HTTP status code should a Flask API return when a request is successful and data is sent back?
easy
A. 200 OK
B. 404 Not Found
C. 500 Internal Server Error
D. 201 Created
Solution
Step 1: Understand the meaning of status codes
200 means the request was successful and the server is returning the requested data.
Step 2: Match the code to the scenario
Since the request succeeded and data is returned, 200 OK is the correct code.
Final Answer:
200 OK -> Option A
Quick Check:
Success response = 200 OK [OK]
Hint: Success with data? Use 200 OK [OK]
Common Mistakes:
Confusing 201 Created with simple success
Using 404 when resource exists
Using 500 for client errors
2. Which of the following is the correct way to return a JSON response with a 201 status code in Flask?
easy
A. return data, code=201
B. return data, status=201
C. return json.dumps(data), 201
D. return jsonify(data), 201
Solution
Step 1: Recall Flask's return syntax for JSON and status
Flask uses jsonify() to convert data to JSON and returns a tuple (response, status_code).
Step 2: Identify the correct syntax
return jsonify(data), 201 correctly uses jsonify(data), 201 to return JSON with status 201.
Final Answer:
return jsonify(data), 201 -> Option D
Quick Check:
Flask JSON + status = jsonify(data), 201 [OK]
Hint: Use jsonify() and return tuple (data, status) [OK]
Common Mistakes:
Using json.dumps without jsonify
Incorrect keyword arguments like status= or code=
Returning raw data without JSON conversion
3. Consider this Flask route code:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/item/')
def get_item(id):
items = {1: 'apple', 2: 'banana'}
if id in items:
return jsonify({'item': items[id]}), 200
else:
return jsonify({'error': 'Item not found'}), 404
What HTTP status code will be returned when accessing /item/3?
medium
A. 200
B. 404
C. 500
D. 201
Solution
Step 1: Check if id 3 exists in items dictionary
Items only have keys 1 and 2, so 3 is not found.
Step 2: Identify the returned status code for missing item
The else block returns 404 Not Found with an error message.
Final Answer:
404 -> Option B
Quick Check:
Missing resource = 404 Not Found [OK]
Hint: Missing item? Return 404 Not Found [OK]
Common Mistakes:
Assuming 200 even if item missing
Confusing 404 with 500 server error
Returning 201 for missing resource
4. This Flask API code is intended to return a 400 Bad Request if the 'name' field is missing in JSON input:
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
if 'name' not in data:
return {'error': 'Name required'}, 400
return {'message': 'Added'}, 201
What is the main problem with this code?
medium
A. It returns a dict instead of using jsonify
B. It returns 201 instead of 200 on success
C. It does not import request from flask
D. It uses wrong status code for missing name
Solution
Step 1: Check imports needed for request
The code uses request.get_json() but does not show importing request from flask.
Step 2: Identify the error caused by missing import
Without importing request, the code will raise a NameError at runtime.
Final Answer:
It does not import request from flask -> Option C
Quick Check:
Missing import request causes error [OK]
Hint: Always import request to use request.get_json() [OK]
Common Mistakes:
Ignoring missing imports causing runtime errors
Thinking returning dict is invalid (Flask accepts dict)
Confusing 201 Created as wrong success code here
5. You want to create a Flask API endpoint that creates a new user. If the username already exists, return 400 Bad Request. If creation succeeds, return 201 Created with the new user's ID. Which code snippet correctly implements this behavior?
hard
A. def create_user():
data = request.get_json()
if data['username'] in users:
return {'error': 'User exists'}, 400
new_id = len(users) + 1
users[new_id] = data['username']
return {'id': new_id}, 201
B. def create_user():
data = request.get_json()
if data['username'] in users:
return {'error': 'User exists'}, 404
new_id = len(users) + 1
users[new_id] = data['username']
return {'id': new_id}, 200
C. def create_user():
data = request.get_json()
if data['username'] in users:
return {'error': 'User exists'}, 500
new_id = len(users) + 1
users[new_id] = data['username']
return {'id': new_id}, 201
D. def create_user():
data = request.get_json()
if data['username'] in users:
return {'error': 'User exists'}, 201
new_id = len(users) + 1
users[new_id] = data['username']
return {'id': new_id}, 400
Solution
Step 1: Check status code for existing user
400 Bad Request is correct when username already exists, indicating client error.
Step 2: Check status code for successful creation
201 Created is the correct code for successful resource creation.
Step 3: Verify code matches these codes
def create_user():
data = request.get_json()
if data['username'] in users:
return {'error': 'User exists'}, 400
new_id = len(users) + 1
users[new_id] = data['username']
return {'id': new_id}, 201 returns 400 for existing user and 201 for success, matching requirements.
Final Answer:
Option A code snippet -> Option A
Quick Check:
Existing user = 400, success = 201 [OK]
Hint: Use 400 for bad input, 201 for successful creation [OK]
Common Mistakes:
Using 404 or 500 for existing user error
Returning 200 instead of 201 on creation
Mixing up success and error codes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.