Authentication overview
Mailchimp provides two primary methods for authenticating API requests: API keys and OAuth 2.0. The choice between these methods depends on the type of integration being developed. API keys are suitable for server-side applications that require direct access to a single Mailchimp account, such as custom scripts or internal tools. They grant broad permissions associated with the user account that generated the key.
OAuth 2.0 is designed for third-party applications that need to access Mailchimp accounts on behalf of multiple users without storing their Mailchimp credentials. This method provides a secure, token-based authorization flow, allowing users to grant specific permissions to an application and revoke them at any time. Mailchimp's implementation of OAuth 2.0 follows standard OAuth 2.0 authorization framework principles, utilizing authorization codes and refresh tokens for sustained access.
Both authentication methods require secure handling of credentials to prevent unauthorized access to Mailchimp data and functionality. Developers should consider the scope of access needed and the security implications of each method when designing their integrations.
Supported authentication methods
Mailchimp supports the following authentication methods for its API:
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Direct server-to-server integrations, internal tools, scripts accessing a single Mailchimp account. | Moderate. Requires secure storage and transmission. Access is tied to the generating user's permissions. |
| OAuth 2.0 | Third-party applications, public integrations, applications needing delegated access to multiple user accounts. | High. Token-based, revocable access. User credentials are not shared with the application. Follows IETF RFC 6749 for OAuth 2.0. |
When an API key is used, it must be included in the HTTP request as part of the Basic Authentication header. The username can be any string, and the API key serves as the password. For OAuth 2.0, an access token is obtained after the user authorizes the application, and this token is then used in the Authorization: Bearer header for API requests. Mailchimp's API documentation provides specific instructions on constructing these headers for Mailchimp API key authentication and Mailchimp OAuth 2.0 implementation.
Getting your credentials
API Key Generation
To generate an API key for your Mailchimp account:
- Log in to your Mailchimp account.
- Navigate to Profile > Extras > API keys.
- Click the Create A Key button.
- Mailchimp will generate a new API key. Copy this key immediately, as it will be displayed only once in its entirety.
- Label your API key for future reference to remember its purpose and associated application.
Each API key is tied to the user account that created it and inherits that user's permissions. It is recommended to create separate API keys for distinct applications or integrations to facilitate easier auditing and revocation if necessary. For detailed steps, refer to the Mailchimp API key creation guide.
OAuth 2.0 Credential Setup
Setting up OAuth 2.0 involves registering your application with Mailchimp to obtain a Client ID and Client Secret:
- Log in to the Mailchimp Developer Console.
- Create a new application or select an existing one.
- In your application settings, you will find your Client ID and Client Secret.
- Configure the Redirect URI(s), which are the URLs where Mailchimp will redirect the user after they grant or deny access to your application. These must be exact matches to what Mailchimp expects.
The OAuth 2.0 flow typically involves:
- Directing the user to Mailchimp's authorization endpoint with your Client ID and Redirect URI.
- The user grants permission, and Mailchimp redirects back to your Redirect URI with an authorization code.
- Your application exchanges this authorization code for an access token and a refresh token using your Client ID and Client Secret.
- The access token is then used to make API calls on behalf of the user. The refresh token can be used to obtain new access tokens when the current one expires, ensuring continuous access without requiring the user to re-authorize.
For a complete walkthrough of the OAuth 2.0 process, consult the Mailchimp OAuth 2.0 developer guide.
Authenticated request example
This example demonstrates an authenticated request using an API key in Python. The API key is used for Basic Authentication, where any string can be used as the username, and the API key acts as the password.
import requests
# Replace with your actual Mailchimp API key and datacenter (e.g., us1, eu2)
API_KEY = "YOUR_MAILCHIMP_API_KEY"
DATACENTER = "us1"
# The base URL for the Mailchimp API v3.0
API_BASE_URL = f"https://{DATACENTER}.api.mailchimp.com/3.0"
# The endpoint to retrieve information about the current account
ENDPOINT = f"{API_BASE_URL}/" # Root endpoint for account info
# Set up Basic Authentication header
# The username can be any string, the password is the API key
headers = {
"Authorization": f"Basic anystring:{API_KEY}"
}
try:
response = requests.get(ENDPOINT, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
account_info = response.json()
print("Mailchimp Account Information:")
print(f"Account Name: {account_info.get('account_name')}")
print(f"Contact Email: {account_info.get('contact').get('email')}")
print(f"Total Contacts: {account_info.get('total_subscribers')}")
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 Code: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
In this Python example, requests.get() sends an HTTP GET request to the Mailchimp API. The Authorization header is constructed using the Basic scheme, where anystring is a placeholder username and YOUR_MAILCHIMP_API_KEY is your actual API key. The datacenter (e.g., us1) is crucial as it forms part of your API base URL and corresponds to the region where your Mailchimp account is hosted. You can find your datacenter prefix at the end of your API key (e.g., xxxxxxxxxxxxxxx-us1).
For more examples in other languages and detailed API reference, visit the Mailchimp API reference documentation.
Security best practices
Securing your Mailchimp API integrations is critical to protect sensitive data and prevent unauthorized access. Adhere to these best practices:
- Protect API Keys: Treat API keys as sensitive as passwords. Do not hardcode them directly into your application's source code. Instead, use environment variables, secure configuration files, or a secrets management service (e.g., AWS Secrets Manager, Google Cloud Secret Manager) to store and retrieve them.
- Use Environment Variables: For server-side applications, loading API keys from environment variables at runtime is a common and recommended practice. This prevents keys from being committed to version control systems.
- Restrict API Key Access: Limit who has access to generate or view API keys within your Mailchimp account. Utilize Mailchimp's user permissions to ensure only necessary personnel can manage API keys.
- Rotate API Keys Regularly: Periodically generate new API keys and revoke old ones. This minimizes the risk associated with a compromised key over time. If a key is suspected of being compromised, revoke it immediately.
- Use OAuth 2.0 for Third-Party Apps: For applications that interact with multiple Mailchimp accounts or are publicly accessible, always use OAuth 2.0. This method eliminates the need to handle user credentials directly, reducing security risks.
- Secure OAuth Client Secrets: Like API keys, OAuth Client Secrets must be kept confidential. Store them securely and never expose them in client-side code (e.g., JavaScript in a browser).
- Validate Redirect URIs: When configuring OAuth 2.0, ensure your Redirect URIs are precise and only allow redirects to trusted domains you control. This prevents authorization codes from being intercepted by malicious sites.
- Implement HTTPS/TLS: Always use HTTPS for all communications with the Mailchimp API. This encrypts data in transit, protecting API keys, access tokens, and sensitive data from eavesdropping. Mailchimp's API endpoints enforce HTTPS.
- Log and Monitor API Usage: Implement logging for API requests and responses to monitor for suspicious activity or unauthorized access attempts. Review these logs regularly.
- Error Handling: Implement robust error handling in your application to gracefully manage API errors, including authentication failures. Avoid exposing sensitive error details to end-users.
- Principle of Least Privilege: Design your application to request only the necessary permissions from Mailchimp. For OAuth 2.0, this means requesting the minimum required scopes. For API keys, this implies using an account with appropriate, not excessive, permissions.