Creating label with id via Google Gmail API

2019-06-10 08:54发布

问题:

I am trying to create a label with a custom id using the node library for the Gmail API. The API has a request parameter for setting your own id however when I try to create the label I get the error:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalidArgument",
    "message": "Invalid request"
   }
  ],
  "code": 400,
  "message": "Invalid request"
 }
}

The label is created with no problems when I don't give an id. However for my purposes I need to have a set standard label id. Anyone know what is going on here or if it is just a bug/error with the api? You can try creating your own label for your account and see more of what I am talking about here: https://developers.google.com/apis-explorer/#p/gmail/v1/gmail.users.labels.create

Code to create label:

var service = Google.gmail({version : 'v1', auth : oauth2Client});
service.users.labels.create({
    userId : 'user address here',
    labelListVisibility   : 'labelShow',
    messageListVisibility : 'show',
    name : 'label name here',
    id   : 'label id here'
}, function (err) {
    if (err) {
        throw err;
    } else {
       callback();
    }
});

Thanks!

回答1:

You say "The API has a request parameter for setting your own id", but the documentation at https://developers.google.com/gmail/api/v1/reference/users/labels/create does not show any such field as part of the users.labels.create endpoint.

If you look at https://developers.google.com/gmail/api/v1/reference/users/labels, you'll see an immutable id field, but this is not writable, so the value for this is set by the system rather than by you.

The documentation for users.labels.create also indicates that a fully populated Users object will be returned, so you'll be able to know what the ID for the label you just created was. To do this with the node.js library, you set the callback function to have a second parameter, which will contain the results of the call. So it might look something like this:


var service = Google.gmail({version : 'v1', auth : oauth2Client});
service.users.labels.create({
    userId : 'user address here',
    labelListVisibility   : 'labelShow',
    messageListVisibility : 'show',
    name : 'label name here'
}, function (err, result) {
    if (err) {
        throw err;
    } else {
       console.log( result );
       callback( result );
    }
});

As noted in the comments, you can also use users.labels.list to get a full list of labels for this user.