How should a RESTful API handle pagination in the situation where a client may want the ability to jump to arbitrary pages? Let's assume we are using the Link
header in the way the GitHub API does:
Link: <https://api.github.com/user/repos?page=3&per_page=100>; rel="next", <https://api.github.com/user/repos?page=50&per_page=100>; rel="last"
The API, like many others, returns links to the next page, previous page, first page and last page. This does not account for the relatively common use-case of providing on the client-side links to a range of pages, and not just the next/previous/first/last. If, for example, the request returns 100 pages worth of results, the client may want to allow the ability to jump to an arbitrary page. How should this be done while adhering closely to the concepts of REST?
Some possible options:
- Just let the client infer the other links. You have the first and last page, it may be a reasonable assumption to modify the link to obtain the other pages. This seems to go against HATEOAS (which is always the principle of REST that seems to cause problems).
- Return a link to every page. This seems unwieldy as the potential number of pages could be high.
- Return a link to a small range of pages (perhaps 2 either side of the current page). This seems like a relatively sensible approach but it limits the options clients have when it comes to displaying pagination information.
Best Answer
##The problem is the URL is not RESTful in the GitHub example:
I would rather see actual
URL
that represent the resource exclusively. It is not that hard if you put a little thought into it.###To be truly RESTful the URI should be a resource identifier and nothing else
Parameters make it
RPC
overHTTP
which is the opposite of theREST
paradigm.Using parameters as part of the identifier is a bad practice, regardless of who is doing it.
No parameters and more concise and self describing as well.
###If the list is totally client side then fragment identifiers would be the correct choice:
Since fragments are never set to the server on requests they are totally client side references. Fragment Identifier is considered a sub-location of the resource, which semantically
previous
andnext
are sub-locations ofposts/
The specific example of RFC 5147 is applicable here
http://example.com/document.txt#line=10,20
RFC7233 specifies the binary
RANGE
header. That is a very compelling argument for a customPAGINATION_RANGE
header using the RFC5988Link Header
in the same spirit.###Fragments do not reload the page but do create history:
So you get correct forward/back button behavior for free!