Bird
Raised Fist0
Flaskframework~20 mins

API key authentication concept in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
API Key Authentication Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when a valid API key is provided?

Consider this Flask route that checks for an API key in the request headers. What will the response be if the correct API key is sent?

Flask
from flask import Flask, request, jsonify
app = Flask(__name__)

API_KEY = 'secret123'

@app.route('/data')
def data():
    key = request.headers.get('X-API-KEY')
    if key == API_KEY:
        return jsonify({'message': 'Access granted'})
    else:
        return jsonify({'message': 'Access denied'}), 401
A{"message": "Access granted"}
B{"message": "Access denied"}
C500 Internal Server Error
D404 Not Found
Attempts:
2 left
💡 Hint

Check what happens when the header X-API-KEY matches the API_KEY variable.

📝 Syntax
intermediate
1:30remaining
Which option correctly extracts the API key from request headers?

In Flask, which code snippet correctly retrieves the API key from the request headers?

Akey = request.headers.get('X-API-KEY')
Bkey = request.get_header('X-API-KEY')
Ckey = request.headers['x-api-key']
Dkey = request.header('X-API-KEY')
Attempts:
2 left
💡 Hint

Remember the correct attribute name for headers in Flask's request object.

🔧 Debug
advanced
2:30remaining
Why does this API key check always deny access?

Look at this Flask route code. Why does it always return 'Access denied' even when the correct API key is sent?

Flask
from flask import Flask, request, jsonify
app = Flask(__name__)

API_KEY = 'secret123'

@app.route('/secure')
def secure():
    key = request.headers.get('X-API-KEY')
    if key is API_KEY:
        return jsonify({'message': 'Access granted'})
    else:
        return jsonify({'message': 'Access denied'}), 401
AThe header name 'X-API-KEY' is incorrect and should be lowercase.
BUsing 'is' compares object identity, not string equality, causing the check to fail.
CThe API_KEY variable is not defined in the route function scope.
DFlask requires API keys to be passed as query parameters, not headers.
Attempts:
2 left
💡 Hint

Consider how Python compares strings with 'is' vs '=='.

❓ state_output
advanced
1:30remaining
What is the response status code when no API key is provided?

Given this Flask route, what HTTP status code will the client receive if the request does not include the 'X-API-KEY' header?

Flask
from flask import Flask, request, jsonify
app = Flask(__name__)

API_KEY = 'secret123'

@app.route('/info')
def info():
    key = request.headers.get('X-API-KEY')
    if key == API_KEY:
        return jsonify({'data': 'Here is your info'})
    else:
        return jsonify({'error': 'API key missing or invalid'}), 401
A200
B403
C401
D400
Attempts:
2 left
💡 Hint

Check the status code returned when the API key check fails.

🧠 Conceptual
expert
3:00remaining
Why is API key authentication considered less secure than OAuth?

Choose the best explanation why API key authentication is generally less secure than OAuth for protecting APIs.

AAPI keys encrypt the entire request, while OAuth only encrypts the headers.
BAPI keys require complex token exchanges which slow down the API response time.
COAuth does not support token expiration, so API keys are preferred for security.
DAPI keys are static and sent with every request, making them easier to steal and reuse.
Attempts:
2 left
💡 Hint

Think about how API keys and OAuth tokens are handled and their security features.

Practice

(1/5)
1. What is the main purpose of using an API key in Flask applications?
easy
A. To style the API output
B. To verify that the client is authorized to access the API
C. To speed up the API response time
D. To store user passwords securely

Solution

  1. Step 1: Understand API key role

    An API key is a secret token sent by the client to prove identity.
  2. Step 2: Identify purpose in Flask

    The server checks this key to allow or deny access to API resources.
  3. Final Answer:

    To verify that the client is authorized to access the API -> Option B
  4. Quick Check:

    API key = Authorization [OK]
Hint: API keys prove client identity to server [OK]
Common Mistakes:
  • Thinking API keys speed up responses
  • Confusing API keys with styling tools
  • Using API keys to store passwords
2. Which of the following is the correct way to retrieve an API key from request headers in Flask?
easy
A. api_key = request.cookies.get('X-API-KEY')
B. api_key = request.args['X-API-KEY']
C. api_key = request.form['X-API-KEY']
D. api_key = request.headers.get('X-API-KEY')

Solution

  1. Step 1: Identify where API keys are usually sent

    API keys are commonly sent in HTTP headers for security.
  2. Step 2: Use Flask syntax to get header value

    Use request.headers.get('Header-Name') to safely retrieve header values.
  3. Final Answer:

    api_key = request.headers.get('X-API-KEY') -> Option D
  4. Quick Check:

    Headers use request.headers.get() [OK]
Hint: Use request.headers.get() for header values [OK]
Common Mistakes:
  • Using request.args for headers
  • Trying to get API key from form data
  • Looking for API key in cookies
3. Given this Flask code snippet, what will be the response if the client sends a request with header X-API-KEY: wrongkey?
from flask import Flask, request, jsonify
app = Flask(__name__)

VALID_API_KEY = 'secret123'

@app.route('/data')
def data():
    api_key = request.headers.get('X-API-KEY')
    if api_key == VALID_API_KEY:
        return jsonify({'message': 'Access granted'})
    else:
        return jsonify({'error': 'Unauthorized'}), 401
medium
A. {"error": "Unauthorized"}
B. {"message": "Access granted"}
C. 500 Internal Server Error
D. Empty response with status 200

Solution

  1. Step 1: Check API key comparison

    The code compares the header key to 'secret123'. 'wrongkey' does not match.
  2. Step 2: Determine response for wrong key

    Since keys differ, the else block returns a JSON error with status 401.
  3. Final Answer:

    {"error": "Unauthorized"} -> Option A
  4. Quick Check:

    Wrong key = Unauthorized error [OK]
Hint: Wrong key triggers 401 Unauthorized JSON error [OK]
Common Mistakes:
  • Assuming any key grants access
  • Expecting 500 error for wrong key
  • Thinking response is empty
4. Identify the error in this Flask API key check code:
from flask import Flask, request
app = Flask(__name__)

VALID_KEY = 'abc123'

@app.route('/info')
def info():
    api_key = request.headers['X-API-KEY']
    if api_key = VALID_KEY:
        return 'Access allowed'
    else:
        return 'Access denied', 403
medium
A. Using single equals (=) instead of double equals (==) in if condition
B. Accessing headers with request.headers.get() instead of []
C. Missing return type for response
D. Route decorator syntax is incorrect

Solution

  1. Step 1: Check if condition syntax

    The if statement uses '=' which is assignment, not comparison.
  2. Step 2: Correct comparison operator

    Use '==' to compare api_key and VALID_KEY for equality check.
  3. Final Answer:

    Using single equals (=) instead of double equals (==) in if condition -> Option A
  4. Quick Check:

    Comparison needs '==' not '=' [OK]
Hint: Use '==' for comparison, '=' is assignment [OK]
Common Mistakes:
  • Confusing '=' with '==' in conditions
  • Thinking request.headers['X-API-KEY'] is wrong
  • Believing return type must be explicit
5. You want to protect multiple Flask routes using the same API key check without repeating code. Which approach is best to implement this efficiently?
hard
A. Copy the API key check code inside every route function
B. Check the API key only in the first route and assume others are safe
C. Create a decorator function that checks the API key before running the route function
D. Use a global variable to store the API key and skip checks

Solution

  1. Step 1: Understand code reuse for API key checks

    Repeating code in every route is inefficient and error-prone.
  2. Step 2: Use a decorator to wrap routes

    A decorator can run the API key check before the route logic, applying it to many routes cleanly.
  3. Final Answer:

    Create a decorator function that checks the API key before running the route function -> Option C
  4. Quick Check:

    Decorator = reusable API key check [OK]
Hint: Use decorators to avoid repeating API key checks [OK]
Common Mistakes:
  • Copy-pasting code in every route
  • Skipping checks on some routes
  • Using global variables to bypass security
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