Bird
Raised Fist0
Rest APIprogramming~20 mins

API key authentication in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
API Key Authentication Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this API key check code?

Consider this Python Flask code snippet that checks an API key sent in the request headers. What will be the HTTP status code returned if the client sends the header API-Key: 12345?

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

VALID_API_KEY = 'abcde'

@app.route('/data')
def data():
    api_key = request.headers.get('API-Key')
    if api_key != VALID_API_KEY:
        return jsonify({'error': 'Unauthorized'}), 401
    return jsonify({'data': 'Secret data'})

# Assume client sends header API-Key: 12345
A401 with JSON {'error': 'Unauthorized'}
B200 with JSON {'data': 'Secret data'}
C500 Internal Server Error
D404 Not Found
Attempts:
2 left
💡 Hint

Check if the API key sent matches the valid key.

🧠 Conceptual
intermediate
1:00remaining
Which header is commonly used to send API keys?

When authenticating API requests using API keys, which HTTP header is most commonly used to send the API key?

AAccept
BAuthorization
CUser-Agent
DContent-Type
Attempts:
2 left
💡 Hint

Think about the header used for credentials.

🔧 Debug
advanced
2:00remaining
What error does this API key validation code raise?

Look at this JavaScript Express middleware that checks for an API key. What error will occur when a request without the api_key query parameter is sent?

Rest API
function checkApiKey(req, res, next) {
  if (req.query.api_key.length !== 10) {
    return res.status(401).send('Invalid API key');
  }
  next();
}

// Middleware used in Express app
ANo error, passes middleware
B401 response with 'Invalid API key'
CTypeError: Cannot read property 'length' of undefined
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint

What happens if req.query.api_key is missing?

📝 Syntax
advanced
1:30remaining
Which option correctly extracts API key from a Bearer token header?

Given the HTTP header Authorization: Bearer abc123xyz, which JavaScript code correctly extracts the API key abc123xyz?

Rest API
const authHeader = req.headers['authorization'];
Aconst apiKey = authHeader.slice(7);
Bconst apiKey = authHeader.replace('Bearer', '');
Cconst apiKey = authHeader.substring(7);
Dconst apiKey = authHeader.split(' ')[1];
Attempts:
2 left
💡 Hint

Remember the space after 'Bearer' in the header value.

🚀 Application
expert
2:30remaining
How many items are in the API key store after these operations?

Consider this Python code that manages API keys in a dictionary. How many keys remain after running all lines?

Rest API
api_keys = {'user1': 'key123', 'user2': 'key456', 'user3': 'key789'}

# Remove user2's key
api_keys.pop('user2')

# Add a new key for user4
api_keys['user4'] = 'key000'

# Update user1's key
api_keys['user1'] = 'key321'

# Remove a non-existing user5 key safely
api_keys.pop('user5', None)
A3
B4
C2
D5
Attempts:
2 left
💡 Hint

Count keys after each operation carefully.

Practice

(1/5)
1. What is the main purpose of an API key in API key authentication?
easy
A. To store user passwords securely
B. To encrypt the data sent between client and server
C. To control and restrict access to the API
D. To speed up the API response time

Solution

  1. Step 1: Understand the role of API keys

    API keys are used to identify and authorize clients accessing an API.
  2. Step 2: Differentiate from other security methods

    API keys do not encrypt data or store passwords; they control access.
  3. Final Answer:

    To control and restrict access to the API -> Option C
  4. Quick Check:

    API key = Access control [OK]
Hint: API keys control who can use the API, not data encryption [OK]
Common Mistakes:
  • Confusing API keys with encryption keys
  • Thinking API keys store user passwords
  • Assuming API keys improve speed
2. Which of the following is the correct way to send an API key in an HTTP request header?
easy
A. Key: YOUR_API_KEY
B. Api-Key: YOUR_API_KEY
C. Authorization: Bearer YOUR_API_KEY
D. X-API-KEY: YOUR_API_KEY

Solution

  1. Step 1: Identify common header names for API keys

    Many APIs use the header 'X-API-KEY' to send the API key securely.
  2. Step 2: Differentiate from other header formats

    'Authorization: Bearer' is for tokens, not API keys; 'Api-Key' and 'Key' are less standard.
  3. Final Answer:

    X-API-KEY: YOUR_API_KEY -> Option D
  4. Quick Check:

    Standard header = X-API-KEY [OK]
Hint: API keys usually go in 'X-API-KEY' header [OK]
Common Mistakes:
  • Using 'Authorization: Bearer' for API keys
  • Sending API key as 'Key' header
  • Confusing API key with OAuth token
3. Consider this Python code snippet using the requests library to call an API with an API key:
import requests
headers = {"X-API-KEY": "12345"}
response = requests.get("https://api.example.com/data", headers=headers)
print(response.status_code)
What will this code print if the API key is valid and the request succeeds?
medium
A. 401
B. 200
C. 404
D. 500

Solution

  1. Step 1: Understand HTTP status codes

    200 means success, 401 means unauthorized, 404 means not found, 500 means server error.
  2. Step 2: Analyze the code behavior with valid API key

    With a valid API key, the server should authorize the request and respond with 200.
  3. Final Answer:

    200 -> Option B
  4. Quick Check:

    Valid key = 200 OK [OK]
Hint: Valid API key means HTTP 200 success code [OK]
Common Mistakes:
  • Confusing 401 Unauthorized with success
  • Assuming 404 means invalid key
  • Thinking 500 is related to API key
4. You have this code snippet to send an API key in a URL parameter:
import requests
url = "https://api.example.com/data?api_key=12345"
response = requests.get(url)
print(response.status_code)
The server always returns 401 Unauthorized. What is the most likely problem?
medium
A. The API key value is incorrect
B. The URL is missing HTTPS
C. The API key should be sent in headers, not URL parameters
D. The requests library does not support URL parameters

Solution

  1. Step 1: Check if sending API key in URL is allowed

    Many APIs accept API keys in URL parameters, so this is often valid.
  2. Step 2: Consider the 401 Unauthorized response

    401 usually means invalid or missing credentials, so the key value is likely wrong.
  3. Final Answer:

    The API key value is incorrect -> Option A
  4. Quick Check:

    401 = Invalid credentials [OK]
Hint: 401 usually means wrong or missing API key value [OK]
Common Mistakes:
  • Assuming URL parameters never work for API keys
  • Ignoring that 401 means invalid credentials
  • Thinking requests library can't send URL parameters
5. You want to secure your API by rotating API keys regularly. Which approach best ensures security while allowing clients to continue using the API without interruption?
hard
A. Generate a new key, distribute it, then disable the old key after a grace period
B. Generate a new key and immediately disable the old key
C. Keep using the same key indefinitely to avoid client issues
D. Send the API key in the URL to make it easier to update

Solution

  1. Step 1: Understand key rotation best practices

    Rotating keys means replacing old keys with new ones to improve security.
  2. Step 2: Ensure clients have time to update keys

    Disabling old keys immediately can break clients; a grace period avoids this.
  3. Final Answer:

    Generate a new key, distribute it, then disable the old key after a grace period -> Option A
  4. Quick Check:

    Grace period = smooth key rotation [OK]
Hint: Use grace period when rotating keys to avoid downtime [OK]
Common Mistakes:
  • Disabling old key immediately causing client failures
  • Never rotating keys risking security
  • Sending keys in URL exposing them