0
0
Flaskframework~10 mins

API key authentication concept in Flask - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the Flask class.

Flask
from flask import [1]
Drag options to blanks, or click blank then click option'
AFlask
BRequest
Cjsonify
DBlueprint
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of Flask
Using lowercase flask instead of Flask
2fill in blank
medium

Complete the code to get the API key from request headers.

Flask
api_key = request.headers.get('[1]')
Drag options to blanks, or click blank then click option'
AAuthorization
BX-API-KEY
CContent-Type
DUser-Agent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Authorization' header instead
Using 'Content-Type' header
3fill in blank
hard

Fix the error in the code to check if the API key matches the expected key.

Flask
if api_key != [1]:
    return {'error': 'Unauthorized'}, 401
Drag options to blanks, or click blank then click option'
Aapi_key
Bmysecretkey
CNone
D'mysecretkey'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes around the key
Comparing api_key to itself
4fill in blank
hard

Fill both blanks to create a Flask route that requires API key authentication.

Flask
@app.route('/data', methods=[[1]])
def get_data():
    api_key = request.headers.get('X-API-KEY')
    if api_key != 'mysecretkey':
        return [2], 401
    return {'data': 'Here is your data'}
Drag options to blanks, or click blank then click option'
A'GET'
B{'error': 'Unauthorized'}
C'POST'
D{'message': 'Success'}
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST instead of GET
Returning success message on unauthorized
5fill in blank
hard

Fill all three blanks to complete the Flask app with API key check and run the server.

Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/info', methods=[[1]])
def info():
    key = request.headers.get('X-API-KEY')
    if key != [2]:
        return [3], 401
    return {'info': 'Secret info'}

if __name__ == '__main__':
    app.run(debug=True)
Drag options to blanks, or click blank then click option'
A'GET'
B'supersecret'
C{'error': 'Unauthorized'}
D'POST'
Attempts:
3 left
💡 Hint
Common Mistakes
Using POST method
Not quoting the API key
Returning success on wrong key