Mithc
Mithc

Reputation: 891

SendGrid API Returns "{List} does not exist"

I'm trying to add an email address to a SendGrid list, which is the only list that exists on my account. I can retrieve the list successfully and send email, but I can't add emails to a contact list.

This is my approach (following the example on Email API Reference and authenticating following Authentication API Reference):

<?php
$API_KEY = getenv('SENDGRID_API_KEY'); // Environment variable sourced correctly

$request_url =  "https://api.sendgrid.com/api/newsletter/lists/email/add.json";
$headers = array(
    "Authorization: Bearer $API_KEY",
    "ContentType: application/json"
);
$data = array(
    "email" => "[email protected]",
    "name" => 'Stackoverflow'
);
$params = array(
    'api_user'  => $sendgrid_user,
    'api_key'   => $sendgrid_pass,
    'list'      => "TestList",
    'data'      => json_encode($data)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$resp = curl_exec($ch);
curl_close($ch);

print_r($resp);

The output of the below code is:

{
    "error": "TestList does not exist"
}

I know TestList exists because I also tried List all lists [GET] and that shows me this:

{
    "lists": [
        {
            "id": XXXXXX,
            "name": "TestList",
            "recipient_count": 1
        }
    ]
}

What am I doing wrong? What do I'm missing?

Upvotes: 2

Views: 736

Answers (1)

bwest
bwest

Reputation: 9814

You're mixing up two different versions of the API. You're authenticating and GETting your lists via v3, but trying to add to v2.

In v3 recipients have a one-to-many relationship with lists, so you'll need to create the recipient, and then add it to your list

Upvotes: 1

Related Questions