Authentication overview
Klaviyo API authentication provides developers with secure methods to interact with the platform, allowing for the management of customer profiles, email campaigns, SMS messages, and other marketing automation features programmatically. The API utilizes API keys to identify and authorize requests, ensuring that only authorized applications can access and manipulate data within a Klaviyo account. Proper authentication is critical for maintaining data privacy and operational security when integrating third-party systems or building custom applications that interact with Klaviyo.
Klaviyo distinguishes between two primary types of API keys: Public API Keys (also referred to as your Site ID) and Private API Keys. Each serves a distinct purpose and carries different security implications. The choice of key depends on the specific API endpoint being accessed and the nature of the operation being performed. All API interactions should adhere to the principle of least privilege, meaning that credentials should only have the minimum necessary permissions to perform their intended function.
Supported authentication methods
The Klaviyo API primarily relies on API keys for authentication. These keys are unique identifiers that grant access to your Klaviyo account's data and functionalities. While both Public and Private API Keys are used, their application and security requirements differ significantly.
- Public API Key (Site ID): This key is designed for client-side use, such as tracking website activity or identifying users for forms. It is considered less sensitive because it only grants access to publicly available information or actions that do not expose private data. The Public API Key is typically used in JavaScript snippets directly on a website to integrate with Klaviyo's tracking and signup forms.
- Private API Key: This key provides full access to your Klaviyo account's data, including customer profiles, campaigns, lists, and more. It must be kept confidential and should only be used in secure, server-side environments. Exposure of a Private API Key could lead to unauthorized access and manipulation of your Klaviyo data.
The method of transmitting these keys in an API request varies:
- Bearer Token: For most V2 and V3 API endpoints, Private API Keys are typically sent in the
Authorizationheader as a Bearer token. This is a standard and recommended practice for API authentication, as outlined in RFC 6750 for Bearer Token usage. Learn more about Bearer Token usage in OAuth 2.0 from the IETF. - Query Parameter: In certain legacy or specific endpoints, particularly for the V1 API or client-side tracking, API keys might be passed as a query parameter (e.g.,
api_key=your_private_api_keyorcompany_id=your_public_api_key). While functional, passing sensitive keys in query parameters is generally less secure than using HTTP headers because query parameters can be logged by web servers and proxies, or can persist in browser history. Klaviyo's V3 API primarily uses the Bearer token method for private keys to enhance security.
The following table summarizes the key types and their appropriate usage:
| Method | When to Use | Security Level |
|---|---|---|
| Public API Key (Site ID) | Client-side tracking, signup forms, public data access | Low (designed for public exposure) |
| Private API Key (Bearer Token) | Server-side operations, full data access (V2/V3 API) | High (must be kept confidential) |
| Private API Key (Query Parameter) | Legacy V1 API endpoints, specific integration needs | Medium (less secure than Bearer token, avoid if possible) |
Getting your credentials
To obtain your Klaviyo API credentials, you need access to your Klaviyo account dashboard. The process involves generating the necessary keys within the API Keys section.
- Log in to your Klaviyo account: Navigate to the Klaviyo dashboard using your administrative credentials.
- Access API Keys settings: In the dashboard, click on your account name in the bottom left corner, then select Settings > API Keys. For detailed instructions, refer to the official Klaviyo API key documentation.
- Locate your Public API Key (Site ID): Your Public API Key, also known as your Site ID, is usually displayed prominently on the API Keys page. It's a short alphanumeric string used for client-side tracking.
- Create a Private API Key: To generate a Private API Key, click the Create Private API Key button. You will be prompted to give your key a name for easy identification (e.g., "My CRM Integration").
- Configure scopes (V3 API): For Private API Keys used with the V3 API, you will be able to configure specific access scopes. This allows you to define precisely what actions and data your API key can access, adhering to the principle of least privilege. For example, if your integration only needs to create profiles, you would grant only the
profiles:writescope. - Copy and store your Private API Key: Once created, the Private API Key will be displayed. It's crucial to copy this key immediately and store it securely, as it will only be shown once. If you lose it, you'll need to generate a new one.
Authenticated request example
This example demonstrates how to make an authenticated request to the Klaviyo V3 API using a Private API Key as a Bearer token. We'll use Python with the requests library to retrieve a list of profiles.
First, ensure you have the requests library installed:
pip install requests
Then, you can make the authenticated request:
import requests
import os
# It's best practice to store sensitive keys in environment variables
# For demonstration, you might temporarily hardcode it, but NEVER in production code
PRIVATE_API_KEY = os.environ.get("KLAVIYO_PRIVATE_API_KEY", "YOUR_KLAVIYO_PRIVATE_API_KEY")
if PRIVATE_API_KEY == "YOUR_KLAVIYO_PRIVATE_API_KEY":
print("Warning: Please set the KLAVIYO_PRIVATE_API_KEY environment variable or replace the placeholder.")
url = "https://a.klaviyo.com/api/profiles/"
headers = {
"accept": "application/json",
"revision": "2024-02-15", # Specify the API revision you are targeting
"Authorization": f"Klaviyo {PRIVATE_API_KEY}"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
print("Successfully retrieved profiles:")
# print(json.dumps(data, indent=2)) # Uncomment to print full response
for profile in data.get("data", [])[:3]: # Print first 3 profiles for brevity
print(f" Profile ID: {profile['id']}, Email: {profile['attributes'].get('email')}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Response status: {e.response.status_code}")
print(f"Response body: {e.response.text}")
In this example:
PRIVATE_API_KEYis loaded from an environment variable for security.- The
Authorizationheader is set toKlaviyo YOUR_PRIVATE_API_KEY, following the V3 API's expectation for Bearer token authentication. - The
revisionheader is included to ensure compatibility with a specific API version, which is a common practice for evolving APIs. - Error handling is included to catch network issues or API-specific errors.
For more language-specific examples and detailed API endpoint information, consult the Klaviyo API reference documentation.
Security best practices
Securing your Klaviyo API credentials and interactions is paramount to protect sensitive customer data and prevent unauthorized access to your marketing operations. Adhere to the following best practices:
- Treat Private API Keys as confidential: Never expose your Private API Keys in client-side code, public repositories, or unsecured environments. They grant extensive access to your Klaviyo account.
- Use environment variables: Store Private API Keys in environment variables or a secure key management system rather than hardcoding them directly into your application code. This prevents accidental exposure and simplifies key rotation. For cloud environments, consider using services like AWS Secrets Manager or Google Secret Manager. Learn more about AWS Secrets Manager for secure credential storage.
- Implement least privilege: When creating Private API Keys, especially for the V3 API, configure them with the narrowest possible scopes (permissions) required for your application's functionality. For instance, if an integration only needs to read profiles, do not grant it write access to campaigns.
- Regularly rotate API Keys: Periodically generate new Private API Keys and revoke old ones. This practice reduces the window of opportunity for a compromised key to be exploited. Establish a rotation schedule based on your organization's security policies.
- Monitor API usage: Keep an eye on your Klaviyo API usage logs and activity. Unusual spikes in requests or unexpected actions could indicate a compromised key.
- Use HTTPS: Always ensure all API requests are made over HTTPS (TLS/SSL). This encrypts communication between your application and the Klaviyo API, preventing eavesdropping and man-in-the-middle attacks.
- Validate and sanitize inputs: When accepting user input that will be used in API requests, always validate and sanitize it to prevent injection attacks and ensure data integrity.
- Error handling: Implement robust error handling in your applications to gracefully manage API errors without exposing sensitive information in error messages.
- IP Whitelisting (if available and applicable): While Klaviyo's API documentation doesn't explicitly highlight IP whitelisting as a primary security feature for API keys, if your environment or a proxy allows for it, restricting API key usage to specific IP addresses can add an extra layer of security. Always consult Klaviyo's official documentation for the most up-to-date security features.