1. Overview
  2. Introduction
  3. API Key Management

API Key Management

1. Environment Variables:


For most scenarios, storing API keys in environment variables is a common and relatively secure practice.

# .env file (DO NOT commit this to version control)
LEMON_API_KEY=your_api_key_here
OPENAI_API_KEY=your_openai_api_key_here

Then, in your code:

Python

import os
from dotenv import load_dotenv

load_dotenv()  # This loads the variables from .env

lemon_api_key = os.getenv('LEMON_API_KEY')
openai_api_key = os.getenv('OPENAI_API_KEY')

2. Secrets Management Services:


For production environments, consider using cloud-based secrets management services:

1. AWS Secrets Manager
2. Google Cloud Secret Manager
3. Azure Key Vault
4. HashiCorp Vault


These services provide secure storage and access to sensitive information like API keys.


3. Configuration Management Tools:


Tools like Ansible, Chef, or Puppet can help manage configurations and secrets across multiple environments.


4. CI/CD Pipeline Integration:


Many CI/CD tools (like Jenkins, GitLab CI, or GitHub Actions) offer ways to securely store and inject secrets into your build and deployment processes.


Here's an example of how you might use environment variables in the context of our earlier Python example:

import os
import openai
import requests
from dotenv import load_dotenv

load_dotenv()  # Load environment variables

def generate_and_send_email(user_data):
    openai_api_key = os.getenv('OPENAI_API_KEY')
    lemon_api_key = os.getenv('LEMON_API_KEY')

    if not openai_api_key or not lemon_api_key:
        raise ValueError("API keys not found. Please check your environment variables.")

    openai.api_key = openai_api_key
    
    # Generate content with OpenAI
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=f"Write an email to {user_data['name']} about their recent activity: {user_data['activity']}",
        max_tokens=200
    )
    email_content = response.choices[0].text.strip()

    # Send email using Lemon API
    response = requests.post(
        'https://app.xn--lemn-sqa.com/api/transactional/send',
        headers={
            'Content-Type': 'application/json',
            'X-Auth-APIKey': lemon_api_key
        },
        json={
            "fromname": "Your SaaS",
            "fromemail": "noreply@yoursaas.com",
            "to": user_data['email'],
            "subject": "Your Activity Update",
            "body": f"<html><body>{email_content}</body></html>"
        }
    )
    return response.json()

# Usage
try:
    result = generate_and_send_email({
        "name": "John",
        "email": "john@example.com",
        "activity": "Completed 5 workouts this week"
    })
    print(result)
except ValueError as e:
    print(f"Error: {e}")

Best Practices for API Key Security:

1. Never hardcode API keys directly in your source code.
2. Don't store API keys in version control systems like Git.
3. Rotate API keys regularly.
4. Use different API keys for development and production environments.
5. Implement the principle of least privilege - only give API keys the permissions they need.
6. Monitor API key usage for any suspicious activity.
7. Educate your team about the importance of API key security.


By following these practices, you can ensure that your integration with the Lemon Email API (and other services) remains secure, even as you scale your applications.


Was this article helpful?
© 2024 Lemón SES