Bird
Raised Fist0
Prompt Engineering / GenAIml~10 mins

API key management in Prompt Engineering / GenAI - Interactive Code Practice

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
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to load the API key from an environment variable.

Prompt Engineering / GenAI
import os
api_key = os.getenv([1])
Drag options to blanks, or click blank then click option'
A"api_key"
BAPI_KEY
C"API_KEY"
Dapi_key
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the environment variable name.
2fill in blank
medium

Complete the code to check if the API key is missing and raise an error.

Prompt Engineering / GenAI
if [1] is None:
    raise ValueError("API key is missing")
Drag options to blanks, or click blank then click option'
Aapi_key is None
Bapi_key
Capi_key == ''
Dnot api_key
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' instead of 'is' to check None.
3fill in blank
hard

Fix the error in the code to securely store the API key in a variable.

Prompt Engineering / GenAI
def store_key():
    [1] = os.getenv("API_KEY")
    return api_key
Drag options to blanks, or click blank then click option'
Aapi_key
BAPI_KEY
Ckey
DapiKey
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than the one returned.
4fill in blank
hard

Fill both blanks to create a function that validates the API key length and raises an error if invalid.

Prompt Engineering / GenAI
def validate_key(key):
    if len(key) [1] 32:
        raise ValueError("Invalid API key length")
    return True
Drag options to blanks, or click blank then click option'
A==
B>
C!=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' for length check.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps API key names to their masked versions if the key length is valid.

Prompt Engineering / GenAI
masked_keys = [1]: key[:4] + '****' + key[-4:] for [2], key in keys.items() if len(key) [3] 32
Drag options to blanks, or click blank then click option'
A{name
Bname
C<=
Dkey
Attempts:
3 left
💡 Hint
Common Mistakes
Missing curly braces in comprehension.
Using wrong comparison operator.

Practice

(1/5)
1. What is the main purpose of an API key in AI services?
easy
A. To improve AI model accuracy
B. To speed up the AI model training
C. To store user data securely
D. To control who can access the AI service

Solution

  1. Step 1: Understand API key role

    An API key acts like a password to allow access to AI services.
  2. Step 2: Identify main purpose

    It controls who can use the service by authenticating requests.
  3. Final Answer:

    To control who can access the AI service -> Option D
  4. Quick Check:

    API key = Access control [OK]
Hint: API keys are like secret passwords for access [OK]
Common Mistakes:
  • Thinking API keys improve model accuracy
  • Confusing API keys with data storage
  • Believing API keys speed up training
2. Which of the following is the correct way to include an API key in a request header?
easy
A. Authorization: Bearer YOUR_API_KEY
B. API-Key: YOUR_API_KEY
C. Key: YOUR_API_KEY
D. Token: YOUR_API_KEY

Solution

  1. Step 1: Recall standard header format

    The common standard is to use 'Authorization' with 'Bearer' followed by the API key.
  2. Step 2: Match correct header syntax

    Authorization: Bearer YOUR_API_KEY matches this standard format exactly.
  3. Final Answer:

    Authorization: Bearer YOUR_API_KEY -> Option A
  4. Quick Check:

    Authorization header uses Bearer token [OK]
Hint: Use 'Authorization: Bearer' for API keys in headers [OK]
Common Mistakes:
  • Using incorrect header names like 'Key' or 'Token'
  • Omitting 'Bearer' keyword
  • Placing API key in URL instead of header
3. Consider this Python code snippet using an API key:
import requests
headers = {"Authorization": "Bearer abc123"}
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 code behavior with valid key

    With a valid API key, the request should succeed and return status code 200.
  3. Final Answer:

    200 -> Option B
  4. Quick Check:

    Valid key + successful request = 200 [OK]
Hint: 200 means success, 401 means unauthorized [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 a request with an API key:
headers = {"Authorization": "Bearer " + api_key}
response = requests.get(url, headers=headers)
But you get a 401 Unauthorized error. What is the most likely cause?
medium
A. The requests library is not imported
B. The URL is misspelled
C. The API key variable is empty or incorrect
D. The server is down

Solution

  1. Step 1: Understand 401 error meaning

    401 Unauthorized means the server rejected the request due to bad or missing credentials.
  2. Step 2: Identify cause related to API key

    If the API key variable is empty or wrong, the Authorization header is invalid, causing 401.
  3. Final Answer:

    The API key variable is empty or incorrect -> Option C
  4. Quick Check:

    401 error = invalid credentials [OK]
Hint: 401 means check your API key value first [OK]
Common Mistakes:
  • Blaming URL spelling for 401 error
  • Ignoring missing import errors
  • Assuming server down causes 401
5. You want to improve security by rotating your API keys regularly. Which approach is best to avoid service interruption?
hard
A. Create a new key, update your app to use it, then delete the old key
B. Delete the old key first, then create a new key
C. Use the same key forever without changes
D. Share your API key publicly to get feedback

Solution

  1. Step 1: Understand key rotation process

    To avoid downtime, keep old key active until new key is working.
  2. Step 2: Choose safe rotation order

    Create new key, update app, confirm it works, then delete old key.
  3. Final Answer:

    Create a new key, update your app to use it, then delete the old key -> Option A
  4. Quick Check:

    Rotate keys safely by overlapping usage [OK]
Hint: Add new key before deleting old one [OK]
Common Mistakes:
  • Deleting old key before new key is ready
  • Never rotating keys at all
  • Sharing keys publicly