PYTHON

Safely Managing and Using API Keys in Python

Learn best practices for securely storing and accessing sensitive API keys in your Python applications using environment variables, preventing exposure in code.

import os
import requests

class ExternalApiClient:
    def __init__(self):
        # Retrieve API key from environment variable
        self.api_key = os.environ.get("MY_EXTERNAL_API_KEY")
        if not self.api_key:
            raise ValueError("MY_EXTERNAL_API_KEY environment variable not set.")
        self.base_url = "https://api.external.com/v1"

    def get_data(self, endpoint, params=None):
        headers = {
            "Authorization": f"Bearer {self.api_key}", # Or 'x-api-key', depending on API
            "Accept": "application/json"
        }
        url = f"{self.base_url}/{endpoint}"

        try:
            response = requests.get(url, headers=headers, params=params)
            response.raise_for_status() # Raise an exception for HTTP errors
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"API call failed: {e}")
            return None

    def post_data(self, endpoint, data):
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
        url = f"{self.base_url}/{endpoint}"

        try:
            response = requests.post(url, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"API post failed: {e}")
            return None

if __name__ == "__main__":
    # Example Usage:
    # Before running, set the environment variable:
    # export MY_EXTERNAL_API_KEY="your_actual_secure_api_key_here"

    try:
        client = ExternalApiClient()
        print("API client initialized successfully.")

        # Example GET request
        print("
Fetching some data...")
        data = client.get_data("items", {"limit": 5})
        if data:
            print("Received data:", data)

        # Example POST request
        print("
Sending some data...")
        post_response = client.post_data("items", {"name": "New Item", "value": 123})
        if post_response:
            print("Post response:", post_response)

    except ValueError as e:
        print(f"Error: {e}")
        print("Please ensure MY_EXTERNAL_API_KEY is set in your environment.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
How it works: This snippet illustrates the critical practice of securing API keys by loading them from environment variables instead of hardcoding them. It defines a Python class for an external API client that uses this securely retrieved key for authentication in HTTP requests. This prevents sensitive credentials from being exposed in source code, version control, or production logs, enhancing application security.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs