Bird
Raised Fist0
Flaskframework~20 mins

HTTP status codes for APIs in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
HTTP Status Code Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What HTTP status code does this Flask API return?
Consider this Flask route. What HTTP status code will the API respond with when accessed?
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/item/<int:id>')
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
A500 when item does not exist, 200 when item exists
BAlways 200 regardless of item existence
C200 when item exists, 404 when item does not exist
D404 always, even if item exists
Attempts:
2 left
💡 Hint
Look at the return statements and the status codes they include.
📝 Syntax
intermediate
2:00remaining
Identify the correct way to return a 201 Created status in Flask
Which option correctly returns a JSON response with HTTP status 201 Created after creating a resource?
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/create', methods=['POST'])
def create():
    new_item = {'id': 3, 'name': 'pear'}
    # Return response here
Areturn jsonify(new_item), 201
Breturn jsonify(new_item, 201)
Creturn jsonify(new_item).status_code(201)
Dreturn new_item, 201
Attempts:
2 left
💡 Hint
Check the syntax for returning a tuple with response and status code.
🔧 Debug
advanced
2:00remaining
Why does this Flask route always return 200 OK even on error?
Examine this Flask route. Why does it always return HTTP 200 OK even when an error occurs?
Flask
from flask import Flask, jsonify
app = Flask(__name__)

@app.route('/divide/<int:a>/<int:b>')
def divide(a, b):
    try:
        result = a / b
        return jsonify({'result': result})
    except ZeroDivisionError:
        return jsonify({'error': 'Cannot divide by zero'})
ABecause ZeroDivisionError is not caught properly
BBecause no status code is specified, Flask defaults to 200 OK
CBecause jsonify automatically sets status to 500 on errors
DBecause the route method is missing @app.errorhandler decorator
Attempts:
2 left
💡 Hint
Think about what happens if you don't specify a status code in Flask.
❓ state_output
advanced
2:00remaining
What is the HTTP status code after this Flask POST request?
Given this Flask route, what HTTP status code will the client receive after a successful POST request?
Flask
from flask import Flask, request, jsonify
app = Flask(__name__)

items = []

@app.route('/items', methods=['POST'])
def add_item():
    data = request.get_json()
    if not data or 'name' not in data:
        return jsonify({'error': 'Missing name'}), 400
    items.append(data['name'])
    return jsonify({'message': 'Item added'}), 201
A200 OK
B500 Internal Server Error
C400 Bad Request
D201 Created
Attempts:
2 left
💡 Hint
Check the return statement after adding the item.
🧠 Conceptual
expert
2:00remaining
Which HTTP status code best fits this API scenario?
You have an API endpoint that updates a user's profile. The update is successful but does not return any content. Which HTTP status code should the API return?
A204 No Content
B200 OK
C201 Created
D202 Accepted
Attempts:
2 left
💡 Hint
Think about status codes that indicate success but no response body.

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

  1. Step 1: Understand the meaning of status codes

    200 means the request was successful and the server is returning the requested data.
  2. Step 2: Match the code to the scenario

    Since the request succeeded and data is returned, 200 OK is the correct code.
  3. Final Answer:

    200 OK -> Option A
  4. 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

  1. 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).
  2. Step 2: Identify the correct syntax

    return jsonify(data), 201 correctly uses jsonify(data), 201 to return JSON with status 201.
  3. Final Answer:

    return jsonify(data), 201 -> Option D
  4. 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

  1. Step 1: Check if id 3 exists in items dictionary

    Items only have keys 1 and 2, so 3 is not found.
  2. Step 2: Identify the returned status code for missing item

    The else block returns 404 Not Found with an error message.
  3. Final Answer:

    404 -> Option B
  4. 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

  1. Step 1: Check imports needed for request

    The code uses request.get_json() but does not show importing request from flask.
  2. Step 2: Identify the error caused by missing import

    Without importing request, the code will raise a NameError at runtime.
  3. Final Answer:

    It does not import request from flask -> Option C
  4. 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

  1. Step 1: Check status code for existing user

    400 Bad Request is correct when username already exists, indicating client error.
  2. Step 2: Check status code for successful creation

    201 Created is the correct code for successful resource creation.
  3. 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.
  4. Final Answer:

    Option A code snippet -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard