python-mailchimp

repository·master·Indexed 19 days ago

https://github.com/vingtcinq/python-mailchimp

A straightforward Python client for the MailChimp API v3, built on top of the requests library. It provides an object-oriented interface to interact with MailChimp resources including lists, members, campaigns, automations, reports, templates, and e-commerce stores. The client supports pagination via count and offset, automatic record fetching with get_all, and field filtering to reduce payload size.

Tokens
6.4K
Snippets
17
Records
24
Agent score
16%

What's inside mailchimp3

  1. How resource IDs and hierarchy work in the MailChimp API

    master

    The MailChimp API client uses a hierarchical structure where IDs must be passed explicitly to navigate between levels.

    Key Principles:

    1. ID Persistence: When a method returns a single result (like create()) or takes an ID argument (like app_id or subscriber_hash), the client tracks these IDs.
    2. Scope of IDs: Stored attributes (IDs) are only available at the specific level they were passed or created.
    3. Manual Navigation: To move between levels (e.g., from a List to a Member, or from a Store to an Order), you must explicitly pass the parent IDs again.

    Example Pattern: To access a specific member within a list, you cannot simply call client.members.get(). You must provide the context: client.lists.members.get(list_id='...', subscriber_hash='...').

  2. MailChimp API endpoint structure

    master

    The mailchimp3 client mirrors the official MailChimp API v3 structure. You access endpoints by traversing the object hierarchy starting from the MailChimp client instance.

    Common top-level branches include:

    • campaigns (and sub-resources like actions, content)
    • lists (and sub-resources like members, segments, merge_fields)
    • automations
    • reports (and sub-resources like click_reports, email_activity)
    • templates
    • stores (and sub-resources like products, orders)
    • file_manager_files / file_manager_folders
    MailChimp
    +- Root
    +- Authorized Apps
    +- Automations
    |  +- Actions
    |  +- Emails
    |  |  +- Actions
    |  |  +- Queues
    |  +- Removed Subscribers
    +- Batch Operations
    +- Batch Webhooks
    +- Campaign Folders
    +- Campaigns
    |  +- Actions
    |  +- Content
    |  +- Feedback
    |  +- Send Checklist
    +- Conversations
    |  +- Messages
    +- Customer Journeys
    +- Stores
    |  +- Carts
    |  |  +- Lines
    |  |  +- Customers
    |  |  +- Orders
    |  |  |  +- Lines
    |  |  +- Products
    |  |     +- Images
    |  |     +- Variants
    |  |  +- Promo Rules
    |  |     +- Promo Codes
    +- File Manager Files
    +- File Manager Folders
    +- Landing Pages
    |  +- Actions
    |  +- Content
    +- Lists
    |  +- Abuse Reports
    |  +- Activity
    |  +- Clients
    |  +- Growth History
    |  +- Interest Categories
    |  |  +- Interests
    |  +- Members
    |  |  +- Activity
    |  |  +- Events
    |  |  +- Goals
    |  |  +- Notes
    |  |  +- Tags
    |  +- Merge Fields
    |  +- Segments
    |  |  +- Segment Members
    |  +- Signup Forms
    |  +- Twitter Lead Generation Carts
    |  +- Webhooks
    +- Ping
    +- Reports
    |  +- Campaign Abuse
    |  +- Campaign Advice
    |  +- Campaign Open reports
    |  +- Click Reports
    |  |  +- Members
    |  +- Domain Performance
    |  +- EepURL Reports
    |  +- Email Activity
    |  +- Google Analytics
    |  +- Location
    |  +- Sent To
    |  +- Sub-Reports
    |  +- Unsubscribes
    +- Search Campaigns
    +- Search Members
    +- Template Folders
    +- Templates
       +- Default Content
  3. Understand MailChimp API endpoint hierarchy and ID scoping

    master

    The MailChimp API is organized into a hierarchical structure of endpoints. Many methods require specific IDs (e.g., app_id, workflow_id, list_id, or subscriber_hash) to target specific resources.

    Important Scoping Rule: Stored attributes like IDs are only available at the specific level they were passed or created. To move between levels (e.g., from a List to a specific Member), you must pass the parent ID again. For example, to access a member, you must provide both the list_id and the subscriber_hash.

  4. Use pagination with count, offset, and get_all

    master

    For endpoints that support pagination, use the following arguments:

    • count: The number of records to return (defaults to 10).
    • offset: The number of records to skip (defaults to 0).
    • get_all: A boolean argument available on the .all() method. When set to True, the client will loop through all records automatically. When get_all=True, the count defaults to 500 and the provided offset is ignored.

    It is recommended to use a larger count when fetching many records to improve performance and avoid flooding the system with small requests.

    # Example: Fetch 100 members starting from offset 0
    client.lists.members.all('123456', count=100, offset=0)
  5. Fetch all records using get_all

    master

    The all() method on supported endpoints includes a get_all boolean argument. When get_all=True:

    • The client loops through all records automatically until the API returns no more.
    • It ignores the provided offset to ensure a complete fetch.
    • The count defaults to 500 (unless otherwise specified) to improve performance and avoid flooding the system with small requests.
    # Fetches every member in the list regardless of offset
    client.lists.members.all('123456', get_all=True)
  6. Enable request/response logging for the MailChimp client

    master

    The MailChimp client logs request and response details using the mailchimp3.client logging namespace. To capture these details, configure a logger for mailchimp3.client and attach a handler (such as a FileHandler). This is useful for debugging API interactions and inspecting the raw JSON payloads returned by MailChimp.

    import logging
    
    # Configure logging to a file
    fh = logging.FileHandler('/path/to/some/log.log')
    logger = logging.getLogger('mailchimp3.client')
    logger.addHandler(fh)
    
    # Use the client normally; requests/responses will be logged to the file
    client.lists.all(**{'fields': 'lists.date_created'})
  7. Migrate from v2.x to v3.x

    master

    Starting in version 2.1.0, the order of arguments for initializing the MailChimp class was reversed because the username is optional. Additionally, the authentication parameter name changed from mc_secret to mc_api.

    Action required: Reverse the order of your arguments or remove the username argument entirely, and use mc_api instead of mc_secret.

  8. Configure logging for the MailChimp client

    master

    The MailChimp client logs request and response details to the mailchimp3.client logging namespace. To capture these details (such as the full URL and JSON response body) into a file, configure a logger for that specific namespace using Python's logging module.

    import logging
    
    # Setup a file handler to capture request/response details
    fh = logging.FileHandler('/path/to/some/log.log')
    logger = logging.getLogger('mailchimp3.client')
    logger.addHandler(fh)
    
    # Use the client normally
    # The logs will now include details like:
    # GET Request: https://us15.api.mailchimp.com/3.0/lists?fields=lists.date_created
    # GET Response: 200 {"lists": [...]}
  9. Manage Automations and Automation Emails

    master

    Use the client.automations endpoint to manage workflows and their associated emails and queues.

    Automations

    • all(get_all=False): List all automations.
    • get(workflow_id=''): Get a specific automation.
    • actions.pause(workflow_id='') / actions.start(workflow_id=''): Control automation state.

    Automation Emails

    • all(workflow_id=''): List emails in a workflow.
    • get(workflow_id='', email_id=''): Get a specific email.
    • actions.pause(workflow_id='', email_id='') / actions.start(workflow_id='', email_id=''): Control email state.

    Automation Email Queues

    • create(workflow_id='', email_id='', data={}): Create a queue entry.
    • all(workflow_id='', email_id=''): List queue entries.
    • get(workflow_id='', email_id='', subscriber_hash=''): Get a specific queue entry.
    # Example: Pause an automation workflow
    client.automations.actions.pause(workflow_id='my_workflow_id')
    
    # Example: Get emails for a workflow
    emails = client.automations.emails.all(workflow_id='my_workflow_id')
  10. Manage Lists and List Members

    master

    Lists are the core of MailChimp. You can manage the lists themselves, their segments, and the members within them.

    Lists

    • client.lists.all(get_all=False): List all audiences/lists.
    • client.lists.get(list_id=''): Get a specific list.
    • client.lists.update(list_id='', data={}): Update list settings.

    List Members

    • client.lists.members.create(list_id='', data={}): Add a new member.
    • client.lists.members.create_or_update(list_id='', subscriber_hash='', data={}): Upsert a member.
    • client.lists.members.get(list_id='', subscriber_hash=''): Get member details.
    • client.lists.members.delete(list_id='', subscriber_hash=''): Remove a member (unsubscribes them).
    • client.lists.members.delete_permanent(list_id='', subscriber_hash=''): Permanently remove a member.

    Segments & Tags

    • client.lists.segments.all(list_id='', get_all=False): List segments in a list.
    • client.lists.members.tags.update(list_id='', subscriber_hash='', data={}): Update tags for a member.
    # Example: Add a member to a list
    client.lists.members.create(list_id='list_123', data={'email_address': 'user@example.com', 'status': 'subscribed'})
    
    # Example: Get a specific member
    member = client.lists.members.get(list_id='list_123', subscriber_hash='hash_abc')