1

I am trying to use the sendgrid V3 api to add our users to a mailing list. I have constructed the following Ajax request to hit their API, but I keep getting a bad request error. I omitted xhr.setRequestHeader, but I do have a valid API key and it works, because when it is omitted, it returns a 403. Now, I just get 400 for bad request body. I have made my request body look EXACTLY like their example and am still stuck. Example request body from their website

var sendgridData = 
  [
    {
       "marketing_emails": 0,
        "weekly_emails": 0,
        "email": userProfile.email,
        "first_name": "foo",
        "last_name": 'bar',
        "userid": 2,
    }
  ]
 $.ajax({
   method: 'POST',
   url: 'https://api.sendgrid.com/v3/contactdb/recipients',
   data: sendgridData,
   dataType: 'json',
   contentType: 'application/json',
 },
 success: 
 function(res)
 {
   console.log(1, res)

  Modal.close();
   },
   error:
     function(e)
     {
      Modal.close();
      console.log(1,e);
     }
 })
Marc Fletcher
  • 932
  • 1
  • 16
  • 39

1 Answers1

1

Updated with working sample of code and a working jsfiddle:

var apiKey = 'Bearer [API KEY HERE]'

var sendgridData = [
  {
    "marketing_emails": 0,
    "weekly_emails": 0,
    "email": 'someperson@example.com',
    "first_name": "foo",
    "last_name": 'bar',
    "userid": 2,
  }
]

$.ajax({
  method: 'POST',
  url: 'https://api.sendgrid.com/v3/contactdb/recipients',
  data: JSON.stringify(sendgridData),
  dataType: 'json',
  headers: { 'Authorization': apiKey },
  crossDomain: true
})
.done(function(res) {
  console.log(1, res)
})
.fail(function (e) {
  console.log(2, e.status, e.responseText)
})

Let's take a look at the request you're making and go from there. You're making a request to an API and sending along some data, as a Content-Type: application/json;. The API is responding with 400 Bad Request. The reason the API is returning a 400 is because you're sending a request that the server did not like or could not read/parse.

There are a few other things wrong with your code as well:

  1. The endpoint for the Contacts API on v3 is https://api.sendgrid.com/v3/contactdb/recipients
  2. You're not sending along any authentication headers at all. You'll likely not be able to do this client side as this would be a huge security risk exposing your API key for Sendgrid to the world.
brandon927
  • 276
  • 1
  • 12
  • Thanks for the response Brandon. "contacts" is a typo. In my code, it has always been `/contactdb/`, and the error persists. I do also have authorization with a key, but left it out of my question body for obvious reasons. Any other ideas? – Marc Fletcher Feb 24 '17 at 00:55
  • I am able to reproduce the issue and have a working piece of code, I will update my answer with it. – brandon927 Feb 24 '17 at 17:05