Skip to main content

Pagination

Some APIs returns a list of items. Some list can be huge so a paging system will slice the list in pages.

Using paging

Let's take an example. We want to get all customers

Get all customers command
curl -H "x-api-key: cddb5157-12be-42a9-985a-4501c6e6e2fa" https://api.altoviz.com/v1/customers
Get all customers result
HTTP/2 200
content-length: 604
content-type: application/json; charset=utf-8
date: Wed, 13 Sep 2023 13:05:39 GMT
X-PAGE-NEXT: /v1/Customers?PageIndex=2&PageSize=1

[{"id":370,"title":null,"lastName":null,"firstName":null,"email":"julien_fournier@intuit.com","cellPhone":"01 43 57 91 28","phone":null,"companyName":"Auchan hypermarché","billingAddress":{"street":"1 Rue Abel Rabaud","zipcode":"75011","city":"Paris","countryIso":"FR","formattedAddress":"1 Rue Abel Rabaud\n75011 Paris\nFrance","inlineAddress":"1 Rue Abel Rabaud, 75011 Paris, France"},"shippingAddress":null,"companyInformations":{"siret":null,"vatNumber":null},"billingOptions":{"discount":{"type":"Percent","value":0.0},"vatReverseCharge":false,"vendorReference":null},"type":"Company","number":""}]

By default, only the 10 first customers are returned but more are available so the API is setting a header named X-PAGE-NEXT with the path to the next page as value. If there's a previous page, the response will include a header named X-PAGE-PREV with the path to the previous page as value.

PageIndex and PageSize parameters

You can define the expected number of records returned or page size by adding the PageSize parameter to the request.

Get all customers by pages of 5 items
curl -H "x-api-key: cddb5157-12be-42a9-985a-4501c6e6e2fa" https://api.altoviz.com/v1/customers\?PageSize=5

Then, you can move from page to page using the PageIndex parameter.

Get the next 5 customers
curl -H "x-api-key: cddb5157-12be-42a9-985a-4501c6e6e2fa" https://api.altoviz.com/v1/customers\?PageSize=5\&PageIndex=2

You can finally easily go through all customers, page per page, like this :

Get all customers page per page
#!/usr/bin/env bash
data=''
page=1
until [ ! -z $data ]
do
data=$(curl -H "x-api-key: cddb5157-12be-42a9-985a-4501c6e6e2fa" https://api.altoviz.com/v1/customers\?PageIndex=$page\&PageSize=10)
echo Page $page
echo $data
page=$(( $page + 1 ))
done