mario ruiz
mario ruiz

Reputation: 996

Gmail API: messages.list suddenly there's a messages error key despite there's a nextPageToken in the prior iteration

I used to interact with the Gmail API since past year using these tests https://developers.google.com/gmail/api/v1/reference/users/messages/list#try-it but now this examples are failing because seems there are more messages but the next iteration is coming empty.

Problem is in this part of the code:

while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().messages().list(userId=user_id, q=query,
                                         pageToken=page_token).execute()
      messages.extend(response['messages'])

The error is raised when trying to access the response['messages'] as the unique key in the reponse is 'resultSizeEstimate' and is 0. Sounds like the page_token is pointing to a next empty page.

Is someone experiencing this issue as well?

Upvotes: 1

Views: 151

Answers (1)

Tholle
Tholle

Reputation: 112877

If your last page perfectly contains the last email with that particular query, you will get a nextPageToken to a page with a response like this:

{
  "resultSizeEstimate": 0
}

The easiest way around this is to just add a check if messages is part of the response:

while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().messages().list(userId=user_id, q=query, pageToken=page_token).execute()
      if 'messages' in response:
            messages.extend(response['messages'])

Upvotes: 1

Related Questions