Discover how a simple number can save your API from chaos and confusion!
Why HTTP status codes for APIs in Flask? - Purpose & Use Cases
Imagine building an API that just returns data without telling the client if something went wrong or succeeded.
The client has no clear way to know if the request was successful, if data was missing, or if there was a server error.
Without proper status codes, clients guess the result by checking response content, which is slow and unreliable.
This leads to confusion, bugs, and poor user experience because errors are hidden or unclear.
HTTP status codes give a simple, universal way to tell clients what happened with their request.
They make APIs clear and predictable by signaling success, errors, or special conditions instantly.
return jsonify(data)return jsonify(data), 200
Clear communication between API and client, enabling better error handling and smoother user experiences.
A weather app requests data from an API. If the city is not found, the API returns 404, so the app can show a friendly 'City not found' message instead of crashing.
HTTP status codes clearly signal API request results.
They prevent confusion and hidden errors.
Using them improves client-server communication and user experience.
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
