Search code examples
gmailgmail-api

GmailAPI: How can I get the next page of results for a certain query?


I have a certain query that I am using to get results that correspond to a particular search:

response = gmail_service.users().messages().list(userId=user_id, q='from:"[email protected]"', pageToken='').execute()

To get the next page of results, is this the right query:

response = gmail_service.users().messages().list(userId=user_id, q='from:"[email protected]"', pageToken=next_page_token).execute()

I tried not giving the query param, thinking that the next_page_token should contain a reference to the query that generated the previous page, but the results I got did not come from the query parameter. Hence wondering what is the correct way of getting all pages of results corresponding to the query?


Solution

  • Your suspicion is correct. Just supply the same query on your next page fetch and repeat until there is no pageToken in the response. Then you know you have gotten all the results of that particular query.