Mailchimp Marketing Python Client

3.0.80 · active · verified Sat Apr 11

The `mailchimp-marketing` library is the official Python client for the Mailchimp Marketing API. It allows developers to interact with Mailchimp to manage audiences, campaigns, reports, and other marketing-related data programmatically. As of version 3.0.80, it provides a robust interface to the Mailchimp API. The library is auto-generated from a codegen tool, suggesting its release cadence is tied to updates in the underlying Mailchimp API specification.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mailchimp client using API key and server prefix from environment variables and perform a basic API call (ping). It also includes a commented-out example for listing audiences. Ensure `MAILCHIMP_API_KEY` and `MAILCHIMP_SERVER_PREFIX` are set in your environment.

import os
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClient

# It's recommended to store your API key and server prefix as environment variables.
# The server prefix (e.g., 'us1', 'us19') is typically the last part of your API key (e.g., 'YOUR_KEY-us19').

api_key = os.environ.get("MAILCHIMP_API_KEY", "")
server_prefix = os.environ.get("MAILCHIMP_SERVER_PREFIX", "")

# Fallback to extract server prefix from API key if not explicitly set
if not server_prefix and '-' in api_key:
    server_prefix = api_key.split('-')[-1]

if not api_key:
    print("ERROR: MAILCHIMP_API_KEY environment variable not set.")
    print("Please set it to your Mailchimp API key. Example: export MAILCHIMP_API_KEY='yourkey-us1'")
    exit(1)

if not server_prefix:
    print("ERROR: MAILCHIMP_SERVER_PREFIX environment variable not set and could not be extracted from API key.")
    print("Please set it to your Mailchimp server prefix (e.g., 'us1').")
    exit(1)

# Initialize the Mailchimp Marketing Client
client = MailchimpMarketing.Client()
client.set_config({
    "api_key": api_key,
    "server": server_prefix
})

try:
    # Example: Get basic account information (ping the API)
    response = client.ping.get()
    print("Successfully connected to Mailchimp API. Health status:")
    print(response)

    # Example: List all audiences (uncomment to run)
    # print("\nFetching audiences...")
    # audiences_response = client.lists.get_all_lists()
    # if 'lists' in audiences_response:
    #     for list_item in audiences_response['lists']:
    #         print(f"  - Name: {list_item.get('name')}, ID: {list_item.get('id')}")
    # else:
    #     print("No audiences found or unexpected response.")

except ApiClient.ApiException as e:
    print(f"Error calling Mailchimp API: {e}")
    print(f"Status: {e.status}, Reason: {e.reason}, Body: {e.body}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →