Home > OS >  Error 400 when trying to add new contact via SendGrid Contacts API
Error 400 when trying to add new contact via SendGrid Contacts API

Time:08-29

Whenever I attempt to add a new contact via the API I get a 400 error.

Here's my code so far:

        $emails = json_decode('{
            "list_ids": [
                "LIST_ID_HERE",
            ],
            "contacts": [
                {
                    "email": "[email protected]",
                }
            ]
        }');
        $sendgrid = new SendGrid(getenv('SENDGRID_API_KEY'));
        try {
            $response = $sendgrid->client->marketing()->contacts()->put($emails);;
            print $response->statusCode();
            print_r($response->headers());
            print $response->body();
        } catch (Exception $e) {
            echo 'Caught exception: '. $e->getMessage() ."\n";
        }

I've tried it with and without the list_ids, but I get the same response. Here's the exact output from this code:

400Array ( [0] => HTTP/1.1 400 Bad Request [1] => Server: nginx [2] => Date: Sun, 28 Aug 2022 02:41:11 GMT [3] => Content-Type: application/json [4] => Content-Length: 50 [5] => Connection: keep-alive [6] => x-amzn-requestid: 919d1e69-9f8e-46a0-b2d2-72dcca1753c3 [7] => access-control-allow-origin: * [8] => access-control-allow-headers: AUTHORIZATION, Content-Type, On-behalf-of, x-sg-elas-acl, X-Recaptcha, X-Request-Source [9] => x-amz-apigw-id: XjZXMHBWPHcF_pQ= [10] => access-control-allow-methods: PUT,OPTIONS,DELETE,OPTIONS [11] => access-control-expose-headers: Link, Location [12] => x-amzn-trace-id: Root=1-630ad5c7-5825916353f578786cb7c908;Sampled=0 [13] => x-envoy-upstream-service-time: 105 [14] => referrer-policy: strict-origin-when-cross-origin [15] => x-content-type-options: nosniff [16] => x-ratelimit-limit: 200 [17] => x-ratelimit-remaining: 199 [18] => x-ratelimit-reset: 49 [19] => [20] => ) {"errors":[{"field":"","message":"invalid JSON"}]}

I'm assuming I'm doing something wrong, but most of this code was copied directly from the SendGrid API documentation.

I'd appreciate any help, I'm just trying to get this working before we go live next week. I'd hate to have to leave this feature out of the production build.

Thanks!

CodePudding user response:

I think your JSON isn't valid. JSON doesn't handle trailing commas, so your commas after the list ID and after the email address make this invalid. Sadly, json_decode doesn't throw an error when given invalid JSON, it just returns null.

Try this:

        $emails = json_decode('{
            "list_ids": [
                "LIST_ID_HERE"
            ],
            "contacts": [
                {
                    "email": "[email protected]"
                }
            ]
        }');
  • Related