Modify message label Python GMAIL API

Question:

I’m trying to send a post request using the Gmail API. However, I could not find in the documentation the name of the parameter I have to use to send the data.

For example, below is a sample of the code I’m using:

post_data = {
  "addLabelIds": [
    "123456789"
  ]
}

service = build('gmail', 'v1', credentials=credentials)
result = service.users().messages().modify(userId=user_id, id=message_id).execute()

Any guidance would be appreciated, thank you

Asked By: Kyuu

||

Answers:

You need to add the request body as a parameter when calling modify, like this:

result = service.users().messages().modify(userId=user_id, id=message_id, body=post_data).execute()

Reference:

Answered By: Iamblichus

Also, for this to work for me I had to change from this format:

post_data = {
  "addLabelIds": ["123456789"]
}

To this format:

post_data = {
  "addLabelIds": ["123456789"],
  "removeLabelIds": ["IMPORTANT", "CATEGORY_UPDATES", "INBOX"]
}

Looks like the Gmail API needs both the addLabelIds and removeLabelsIds keys.

With only addLabelIds I received the following error from the Gmail API:

An error occurred: <HttpError 400 when requesting
https://gmail.googleapis.com/gmail/v1/users/me/threads/186ce9fdf209a6ec/modify?alt=json
returned "No label add or removes specified". Details: "[{‘message’:
‘No label add or removes specified’, ‘domain’: ‘global’, ‘reason’:
‘invalidArgument’}]">

Answered By: Rodrigo Borges