PYTHON
Securely Managing API Keys with Environment Variables in Python
Learn the best practice for securely handling sensitive API keys by loading them from environment variables in Python, preventing hardcoding.
import os
import requests
def get_api_key(key_name):
"""
Retrieves an API key from environment variables.
Raises an error if the key is not found.
"""
api_key = os.environ.get(key_name)
if not api_key:
raise ValueError(f"Environment variable '{key_name}' not set.")
return api_key
def make_authenticated_api_call(endpoint_url):
"""
Example function demonstrating an API call using a securely retrieved key.
"""
try:
my_api_key = get_api_key("MY_SERVICE_API_KEY")
headers = {
"X-API-Key": my_api_key,
"Accept": "application/json"
}
response = requests.get(endpoint_url, headers=headers)
response.raise_for_status()
return response.json()
except ValueError as e:
print(f"Configuration error: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"API request failed: {e}")
return None
if __name__ == "__main__":
try:
key = get_api_key("MY_SERVICE_API_KEY")
print(f"Successfully retrieved API Key (first 5 chars): {key[:5]}...")
except ValueError as e:
print(f"Error: {e}")
print("
To test, set environment variable:
export MY_SERVICE_API_KEY=\"your_key_here\"
")
How it works: This Python snippet illustrates the crucial practice of loading API keys from environment variables instead of hardcoding them. This enhances security by keeping sensitive credentials out of your codebase and version control. It demonstrates how to access `os.environ` and includes basic error handling if a required key is not set.