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?
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
Check what happens when the header X-API-KEY matches the API_KEY variable.
If the API key in the request header matches the expected key, the route returns a JSON message saying 'Access granted'. Otherwise, it returns 'Access denied' with a 401 status.
In Flask, which code snippet correctly retrieves the API key from the request headers?
Remember the correct attribute name for headers in Flask's request object.
The request.headers is a dictionary-like object. The get method safely retrieves the header value or returns None if missing. Other options are either invalid methods or case-sensitive keys that may cause errors.
Look at this Flask route code. Why does it always return 'Access denied' even when the correct API key is sent?
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
Consider how Python compares strings with 'is' vs '=='.
The 'is' operator checks if two variables point to the same object in memory. For strings, this is unreliable. The correct way is to use '==' to compare string values.
Given this Flask route, what HTTP status code will the client receive if the request does not include the 'X-API-KEY' header?
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
Check the status code returned when the API key check fails.
The route returns a 401 Unauthorized status code when the API key is missing or incorrect, signaling the client must provide valid credentials.
Choose the best explanation why API key authentication is generally less secure than OAuth for protecting APIs.
Think about how API keys and OAuth tokens are handled and their security features.
API keys are usually fixed strings sent with each request, which can be intercepted and reused by attackers. OAuth uses temporary tokens with expiration and scopes, improving security.