0

I'm trying to implement pagination in a concise way and I seem to have a problem that I'm going to describe below.

The client wants the server to return a total number of pages. First I have to do some calculations on the server (apply various filters and that sort of things) and then shape a list of items to return. Then I have to paginate the list according to the items_per_page parameter that I receive from the client in a query string, I also have a default value in case I don't get it from the client. However the client wants to have a total number of pages, so that it could render a list of page links that looks like this << 1 2 3...103 >>. It does not seem right to me to return to the client a JSON object like this:

{
    "total_number_of_pages": 103,
    "users": [{}, {}, ..., {}]
}

total_number_of_pages doesn't really belong here. I could indeed make a special count handler and I like this idea more but perhaps there're better ones. I would like to know how it's implemented in large scale web applications.

GoBear
  • 518
  • 1
  • 5
  • 19
  • You say total_number_of_pages doesn't really belong here. Why not? I implement something similar in a service I built and I return { "pageNum": 0, "pageSize": 10, "size": 110025, "results": [...]} Where size is the total number of results. – bhspencer Jan 24 '19 at 15:49
  • I don't think there's a standard way to paginate a REST API. [This](https://developer.atlassian.com/server/confluence/pagination-in-the-rest-api/) is how Atalassian does it for example. Also see [this other answer](https://stackoverflow.com/questions/12168624/pagination-response-payload-from-a-restful-api). – m0skit0 Jan 24 '19 at 15:50
  • You could call it `total` instead to be more elegant, but i don't see a problem, otherwise. The total number of pages is an important value here an should be part of the response, i think. – bkis Jan 24 '19 at 15:50
  • I don't include the total number of pages. I include the total number of results. If the client wants total pages they can calculate it themselves with the pageSize and total results. – bhspencer Jan 24 '19 at 15:51
  • @bhspencer Answering your question. I just don't quite understand what this object represents, well it could be moved to `metadata` or something like that, but it still looks ugly to me. Returning the total number of results is better though. – GoBear Jan 24 '19 at 15:57
  • The object represents the result of a the query. The result of a query is not just the objects that match but other information as well, total results, perhaps query time in ms etc... – bhspencer Jan 24 '19 at 16:53
  • @bhspencer I know that, I would like it to make sense. I don't want to pile all sorts of information into one json. – GoBear Jan 24 '19 at 18:17
  • Why not. Putting properties on a JSON object that pertain to the response is perfectly reasonable and common. – bhspencer Jan 24 '19 at 18:47

0 Answers0