Search code examples
mailchimpmailing-list

How to create new mailing list using Mailchimp API v.3 and get its id?


I have never used Mailchimp API and I'm wondering if it someone could show me, through example, how to create a new list using this endpoint? And how would I later be able to get the id of this list (using only list name), so I can add subscribers to it?

Thanks


Solution

  • Using PHP and cURL:

    <?php
    
        $apikey = '<api-key>'; // replace with your API key
        $dc = '<data-center>'; // replace with your data center
    
        $data = array( // the information for your new list--not all is required
            "name" => $name,
            "contact" => array (
                "company" => $company,
                "address1" => $address1,
                "address2 => $address2,
                "city" => $city,
                "state" => $state,
                "zip" => $zip,
                "country" => $country,
                "phone" => $phone
            ),
            "permission_reminder" => $permission_reminder,
            "use_archive_bar" => $archive_bars,
            "campaign_defaults" => array(
                "from_name" => $from_name,
                "from_email" => $from_email,
                "subject" => $subject,
                "language" => $language
            ),
            "notify_on_subscribe" => $notify_subs,
            "notify_on_unsubscribe" => $notify_unsubs,
            "email_type_option" => $type,
            "visibility" => $visibility
        );
        $data = json_encode($data); // API requires JSON objects
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, "http://".$dc.".api.mailchimp.com/3.0/lists/"); // ../lists/ URL to create new list resource
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_POSTREQUEST, true); // declare request is POST type
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // set POST data
        curl_setopt($ch, CURLOPT_USERPWD, "user:".$apikey); // HTML Basic Auth
        $output = curl_exec($ch); // execute and capture response
        curl_close($ch); 
        print_r($output); // display API response
    
    ?>
    

    For a neat way to get a feel for the API, I highly recommend playing around in the MailChimp API Playground.