Google GMail API Error: No label add or removes specified

I’m building a small personal web app using the google API, but I’m having an issue with this endpoint: https://developers.google.com/gmail/api/reference/rest/v1/users.messages/modify

I’m trying to invoke this through AJAX, but it keeps telling me:

No label add or removes specified

I feel like I’m following the documentation specifications here, and the error isn’t giving me any more information; I’m not sure what to do.

I’ve also tried adding the addLabelIds argument with no data, but it doesn’t change anything.

I’ve tried looking this issue up but all of the solutions seem to relate to quirks of other API implementations and don’t really seem to apply to my situation. Any help would be appreciated; it’s pretty basic, but here’s my AJAX requests code:

$.ajax({
  url: "https://gmail.googleapis.com/gmail/v1/users/me/messages/" + messageId + "/modify",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + mailToken);
  },
  method: "POST",
  data: {
    "removeLabelIds": ["UNREAD"]
  },
  success: function(data) {
    ele.removeClass("unread");
  },
  fail: function(data) {
    console.log(data);
  }
});

Answer

Okay, I found the solution myself; I’m just going to post it here in-case anyone else is having this issue.

The issue was that you have to make the request using Content-Type: application/json, and POST the request as a JSON string.

Here’s the modified AJAX request that worked.

$.ajax({
    url: "https://content-gmail.googleapis.com/gmail/v1/users/me/messages/" + messageId + "/modify?alt=json",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", "Bearer " + mailToken);
        xhr.setRequestHeader("Content-Type", "application/json");
    },
    method: "POST",
    data: JSON.stringify({
        "removeLabelIds": [
            "UNREAD"
        ]
    }),
    success: function(data) {
        ele.removeClass("unread");
    },
    fail: function(data) {
        console.log(data);
    }
});