HTTP status codes tell the client if the API request worked or if there was a problem. They help both the server and client understand what happened.
HTTP status codes for APIs in Flask
from flask import Flask, jsonify app = Flask(__name__) @app.route('/example') def example(): data = {'message': 'Success!'} return jsonify(data), 200
The status code is returned as the second value in the return statement.
Common status codes include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).
return jsonify({'message': 'Created'}), 201
return jsonify({'error': 'Bad request'}), 400
return jsonify({'error': 'Not found'}), 404
return jsonify({'error': 'Server error'}), 500
This Flask app has two routes: one to get an item by ID and one to create a new item.
It uses HTTP status codes to tell the client if the request was successful or if there was an error like not found or bad request.
from flask import Flask, jsonify, request app = Flask(__name__) items = {'1': 'apple', '2': 'banana'} @app.route('/items/<item_id>', methods=['GET']) def get_item(item_id): if item_id in items: return jsonify({'item': items[item_id]}), 200 else: return jsonify({'error': 'Item not found'}), 404 @app.route('/items', methods=['POST']) def create_item(): data = request.get_json() if not data or 'id' not in data or 'name' not in data: return jsonify({'error': 'Bad request, id and name required'}), 400 if data['id'] in items: return jsonify({'error': 'Item already exists'}), 400 items[data['id']] = data['name'] return jsonify({'message': 'Item created'}), 201 if __name__ == '__main__': app.run(debug=True)
Always return the correct status code to help clients handle responses properly.
Use 2xx codes for success, 4xx for client errors, and 5xx for server errors.
Flask lets you return status codes easily by returning a tuple with the response and code.
HTTP status codes communicate the result of an API request.
Use Flask's return syntax to send both data and status codes.
Common codes: 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not Found), 500 (Internal Server Error).
Practice
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 AQuick Check:
Success response = 200 OK [OK]
- Confusing 201 Created with simple success
- Using 404 when resource exists
- Using 500 for client errors
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 DQuick Check:
Flask JSON + status = jsonify(data), 201 [OK]
- Using json.dumps without jsonify
- Incorrect keyword arguments like status= or code=
- Returning raw data without JSON conversion
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'}), 404What HTTP status code will be returned when accessing
/item/3?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 BQuick Check:
Missing resource = 404 Not Found [OK]
- Assuming 200 even if item missing
- Confusing 404 with 500 server error
- Returning 201 for missing resource
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
if 'name' not in data:
return {'error': 'Name required'}, 400
return {'message': 'Added'}, 201What is the main problem with this code?
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 CQuick Check:
Missing import request causes error [OK]
- Ignoring missing imports causing runtime errors
- Thinking returning dict is invalid (Flask accepts dict)
- Confusing 201 Created as wrong success code here
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 AQuick Check:
Existing user = 400, success = 201 [OK]
- Using 404 or 500 for existing user error
- Returning 200 instead of 201 on creation
- Mixing up success and error codes
Ready to prove it?
Pass the test and this pattern moves unknown
