khaleader
khaleader

Reputation: 183

about pagination gmail api with php

I listed the messages in My App successfully. Now I need to paginate the messages (about 8 in every page). I followed the doc of google but it only gives a pageToken but how to make it work?

Upvotes: 0

Views: 939

Answers (2)

Diego Chavez
Diego Chavez

Reputation: 21

The solution that I found is storing in an array of the front all the tokens that it brings you to be able to go forward and backward between pages, being the index of the array the pages, if it does not bring you the nextPageToken it is because it is the last one, then you pass the current token (of the page where you are) as parameter, and it brings you the list of emails of that page.

Upvotes: 0

Tholle
Tholle

Reputation: 112877

If you list messages, and there still are more results to fetch, the response will contain a nextPageToken.

Request

userId = me
maxResults = 8

GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=8&access_token={YOUR_API_KEY}

Response

{
 "messages": [
  {
   "id": "151596a5055b9412",
   "threadId": "151596a5055b9412"
  },
  {
   "id": "1515915d0fcfd685",
   "threadId": "1515915d0fcfd685"
  },
  {
   "id": "15158e6826ed7587",
   "threadId": "15158e6826ed7587"
  },
  {
   "id": "15158e0e37572671",
   "threadId": "15158e0e37572671"
  },
  {
   "id": "151586443b5b309a",
   "threadId": "151586443b5b309a"
  },
  {
   "id": "15157c4b11732c5c",
   "threadId": "1510f004b81a9de2"
  },
  {
   "id": "151576512d37c9ec",
   "threadId": "1515765122918d37"
  },
  {
   "id": "1515765122918d37",
   "threadId": "1515765122918d37"
  }
 ],
 "nextPageToken": "01770178536732383613", // Here it is!
 "resultSizeEstimate": 26
}

Just include this value as the pageToken in the next request.

Request

userId = me
maxResults = 8
pageToken = 01770178536732383613

GET https://www.googleapis.com/gmail/v1/users/me/messages?maxResults=8&pageToken=01770178536732383613&access_token={YOUR_API_KEY}

Response

{
 "messages": [
  {
   "id": "1515762549119366",
   "threadId": "1513f096ab90fdab"
  },
  {
   "id": "15157616d03a66a1",
   "threadId": "1513f096ab90fdab"
  },
  {
   "id": "151575f958ac69e8",
   "threadId": "1513338849950602"
  },
  {
   "id": "1515756737710843",
   "threadId": "1515756737710843"
  },
  {
   "id": "1515756735412b45",
   "threadId": "1515756735412b45"
  },
  {
   "id": "1515756710eed602",
   "threadId": "1515756710eed602"
  },
  {
   "id": "15157567089a24b0",
   "threadId": "15157567089a24b0"
  },
  {
   "id": "151574a87fefe71d",
   "threadId": "151336e890f46a2c"
  }
 ],
 "nextPageToken": "13534757816909071635",
 "resultSizeEstimate": 27
}

When there is no nextPageToken in the response you have fetched every result there is.

Upvotes: 2

Related Questions