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?
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
Check if the API key sent matches the valid key.
The code compares the API key from the header to the valid key 'abcde'. Since '12345' does not match, it returns a 401 Unauthorized error.
When authenticating API requests using API keys, which HTTP header is most commonly used to send the API key?
Think about the header used for credentials.
The Authorization header is the standard header used to send credentials like API keys or tokens.
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?
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 appWhat happens if req.query.api_key is missing?
If api_key is missing, req.query.api_key is undefined. Accessing length on undefined causes a TypeError.
Given the HTTP header Authorization: Bearer abc123xyz, which JavaScript code correctly extracts the API key abc123xyz?
const authHeader = req.headers['authorization'];Remember the space after 'Bearer' in the header value.
Splitting the string by space and taking the second part extracts the token correctly. Other options either leave spaces or cut wrong lengths.
Consider this Python code that manages API keys in a dictionary. How many keys remain after running all lines?
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)Count keys after each operation carefully.
Initially 3 keys. Removed user2 (down to 2). Added user4 (up to 3). Updated user1 (still 3). Tried to remove user5 (no effect). Final count is 3.