How to add contact in list using (Send Grid) php api

Sanjay Nakate picture Sanjay Nakate · Jun 14, 2016 · Viewed 7.1k times · Source

I am trying to add contact in list using php api but its throwing bellow snippet error

string(51) "{"errors":[{"message":"request body is invalid"}]} " {"email":"[email protected]","first_name":"hh","last_name":"User"}

I am using bellow snippet code:

$url = 'https://api.sendgrid.com/v3';
$request =  $url.'/contactdb/lists/12345/recipients';  //12345 is list_id
$params = array(
'email' => '[email protected]',
'first_name' => 'hh', 
'last_name' => 'User'
  );
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers = 
array("Content-Type: application/json",
"Authorization: Bearer SG.XXXXXXXX");
curl_setopt($ch, CURLOPT_POST, true);   
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}
echo $json_post_fields;

Can any one tell me how to resolve this issue.

Answer

bwest picture bwest · Jun 16, 2016

You should inspect the request that you are sending and compare the JSON in the body to a valid request to really see what's happening. The output of your json_encode here will be an array, but the API expects an object. Your request body needs to be

[{"email":"[email protected]","first_name":"hh","last_name":"User"}]

And what you are doing right now is sending

{"email":"[email protected]","first_name":"hh","last_name":"User"}

You can fix this several ways. You could use your favorite string manipulation functions to append the brackets, or you could skip the encoding and send the JSON as a string (since you're specifying the content type).