How do I retrieve messages from history going from most recent to oldest?

We have several examples on using the history API on our JavaScript docs site including an  example on how to page through history. For other SDKs, it should be easy to translate from JavaScript, but here is a detailed outline of how to implement using any of our SDKs.

For the use case of paging back through history from the most recent message to the oldest message:

Make a request specifying no start point.

  • The result will be in the format of: '[[message1, message2, ... messageN], oldesttimetoken, newesttimetoken]'
  • The order of the messages returned is always oldest to newest
  • The oldest timetoken is for the left-most message
  • The newest timetoken is for the right most message
  • Because we are paging back through history, newest to oldest, in our next request we want to start with the oldest returned message from our previous request
  • Make another request that specifies end=<newest timetoken from previous request>. Because the end point of a request is always exclusive (not included in the result), we can page over the results without any overlap
  • Continue to make requests recursively specifying the end parameter using the newest token from the previous request until the list of messages returned is less than the count requested (max default = 100). For example, if the result set is < 100 when we have requested 100, we can safely assume this is the last page of results.


For example, the first two requests may look like the below:

Get 5 most recent messages


An example use case may specify: "I want to page back through history from most recent to oldest message", but with the added parameter of "But only go back through 5 hours of history". In this case, all history requests (both the initial request, and each paged request afterwards) would also include an end point of 5 hours in the past. This would restrict the results to only messages published within the last 5 hours.  Once paging to a point where there were no messages within the bounds of the specified end point, it would return an empty set.


For example:

Get 5 most recent messages (with an end point 5 hours in past)

Once our result set is empty (or smaller than the requested count) we can safely assume there are no more messages within the given timespan.