Pagination

When you request for a collection of resources, usually, you don't retrieve all of the resources in a single response because there could be thousands of resources in that collection. Using pagination to return only a subset of the collection is usually more efficient, and it also saves network bandwidth and the processing power on the server-side, since it takes less time to run the database query when pagination is used.

There are two ways to do pagination. The first way is offset-based. The API clients send two parameters in the collection's URI: offset (or page) and limit (or count), like in the following example, which is used to get the first 20 orders:

https://api.examplebucks.org/v1/orders?page=1&count=20

The drawback of this approach is that items might either be returned twice or skipped. For example, after the first 20 orders were returned, a new order was created. The collection is sorted by the orders' creation date by default. In this way, when the client requests the second page, the last order shown on the first page will become the first item on the second page. On the other hand, if an order in the first page was deleted after the call, the order that was going to show up as the first item in the second page will be skipped in the request for the second page.

The second way is cursor-based. The API clients will receive a cursor with the result. For example, the following is a response of the getting orders API:

{
"items": [{...}],
"paging": {
"previous":
"https://api.examplebucks.org/v1/orders?count=20&before=101",
"next":
"https://api.examplebucks.org/v1/orders?count=20&after=120"
}
}

As you can see, in the URI of previous and next, the count parameter is used for specifying the page size. The value of the before parameter is the ID of the first order in the result, while the value of the after parameter is the ID of the last order in the result. With cursor-based pagination, no items will be returned twice or skipped. The drawback of this approach is that you cannot jump between pages.

For APIs that support pagination, there should always be a default value for the pagination parameters. For example, when the page parameter is not present, by default, the first page will be returned, and when the count parameter is not found in the URI, by default, the page will contain 20 items.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.172.132