From Delft Solutions
Jump to navigation Jump to search

When APIs need to return a lot of data or if computing which items to show is expensive it is useful to return data in a page-wise fashion.

If the response size is less than 50kb you probably do not want to implement pagination yet. Given that a HTTP request is generally between 1 and 8kB doing pagination below that will generally make things worse.

API Structure

A paginated resource starts at the first page: `/list`. The server can use any Media-Type it wants as long as the corresponding documentation indicates that the client should expect the pagination headers.

If all the responses fit on one page, nothing needs to be done, and no additional headers need to be added.

If there is more data than fits on the first page, the URL for the next page should be set using a Link Header with `rel=next`.

For subsequent pages, if the resource supports iterating backwards, a Link Header with `rel=prev` should be added as well.

If you want to support going to the first and last pages, those can be indicated with `rel=first` and `rel=last`.

Internal Implementation

In order to allow HTTP Caching to do its work it is generally advised to use a reference to the first item on that page instead of a numeric page number. This prevents items falling between pages or being shown twice if items are being added / removed from the list while someone is browsing. An example is: `/list?startat=<item_id>`.

A fast way to do this is by fetching one item more than you want to return in the result and using the id of that element to construct the url for the next page.