📖 Scenario: You are building a simple Flask web API that only allows access to users who provide a valid API key. This is like having a secret password that clients must send with their requests to use your service.
🎯 Goal: Create a Flask app that checks for an API key in the request headers and only allows access if the key matches a predefined secret key.
📋 What You'll Learn
Create a Flask app instance named app
Define a secret API key variable called API_KEY with the value '12345'
Create a route /data that returns JSON data only if the request has the correct API key in the Authorization header
Return a 401 Unauthorized response if the API key is missing or incorrect
💡 Why This Matters
🌍 Real World
API key authentication is a simple way to protect web APIs so only authorized clients can use them. Many services use this method to control access.
💼 Career
Understanding API key authentication is important for backend developers and anyone building or consuming web APIs. It is a common security practice in software development jobs.
Progress0 / 4 steps
1
Set up Flask app and secret API key
Import Flask and jsonify from flask. Create a Flask app instance called app. Define a variable API_KEY and set it to the string '12345'.
Flask
Hint
Use app = Flask(__name__) to create the app. Set API_KEY exactly to '12345'.
2
Create a route to serve data
Add a route decorator @app.route('/data') to define a function called get_data that returns a JSON response with {'message': 'Here is your data'}.
Flask
Hint
Use @app.route('/data') above the function get_data. Return the JSON using jsonify.
3
Check API key in request headers
Import request from flask. Inside get_data, get the Authorization header from request.headers and store it in a variable called api_key. If api_key is not equal to API_KEY, return a JSON response with {'error': 'Unauthorized'} and status code 401.
Flask
Hint
Use request.headers.get('Authorization') to get the API key. Compare it to API_KEY. Return 401 with JSON error if it does not match.
4
Run the Flask app
Add the standard Flask app runner code: if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Hint
Use the standard Python check if __name__ == '__main__': and call app.run(debug=True) inside it.
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
Step 1: Understand API key role
An API key is a secret token sent by the client to prove identity.
Step 2: Identify purpose in Flask
The server checks this key to allow or deny access to API resources.
Final Answer:
To verify that the client is authorized to access the API -> Option B
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
Step 1: Identify where API keys are usually sent
API keys are commonly sent in HTTP headers for security.
Step 2: Use Flask syntax to get header value
Use request.headers.get('Header-Name') to safely retrieve header values.
Final Answer:
api_key = request.headers.get('X-API-KEY') -> Option D
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?
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
Step 1: Check if condition syntax
The if statement uses '=' which is assignment, not comparison.
Step 2: Correct comparison operator
Use '==' to compare api_key and VALID_KEY for equality check.
Final Answer:
Using single equals (=) instead of double equals (==) in if condition -> Option A
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
Step 1: Understand code reuse for API key checks
Repeating code in every route is inefficient and error-prone.
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.
Final Answer:
Create a decorator function that checks the API key before running the route function -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.