First and Foremost: I am using Laravel 5.7.10, Guzzle 6.3.3, PHP 7.2.9, and SendGrid 3.9.6
I only have about 6 months of API experience, so bear with me on the jargan :)
My client Request code which is failing:
$client->request('POST', 'contactdb/recipients', [
'headers' => [
'Authorization' => [MyAPIKey - Correct and Valid],
'Content-Type' => "application/json",
],
'json' => json_encode(
[
'email' => $emailSent['email']
]
),
]);
Under the SendGrid API Documentation, (Contacts API - Recipients /post) (https://sendgrid.com/docs/API_Reference/api_v3.html):
The user should be added as json-encoded 'data' fields. I am trying to avoid sending cURL requests for obnoxious syntax reasons, as well as better error handling. (I have written this in cURL in the past and disliked it.)
However, when I sent a request to this url, which should theoretically add them as a user and assign them a recipient ID, I am having Laravel push this error back to me:
Client error:
POST https://api.sendgrid.com/v3/contactdb/recipients
resulted in a400 BAD REQUEST
response: {"errors":[{"message":"request body is invalid"}]}
I know for a fact that that variable is valid, as I have checked it before this request was sent, so the issue is not the variable as far as I can tell.
Any help would be appreciated - I think that this is a simple syntax error.
I have seen code similar to this
$client->setBody(xyz)
Is this something I should look at?
Edit: Thanks to help, I have learned and figured this out.
Correct and Valid Code that works for me: (Uri is an extension of the main one in contactdb/recipients)
$res = $client->request('POST', 'contactdb/recipients', [
'headers' => [
'Authorization' => My API Key,
],
'json' => [
[
'email' => $emailSent['email']
]
],
]);
As mentioned in the comments and answers, by defining the post as json, you don't have to add the content type or encode it at all. Just comma separate with pipes! :)