Pagination is essential when dealing with large datasets in API responses. It allows clients to retrieve data in smaller, more manageable portions instead of receiving all the data at once. The key elements of pagination include:
- Limit: The maximum number of items to return in a single response. You can set the value using the
per_pageparameter, with a default limit of 100. The value cannot exceed 100. - Cursor: A token or identifier that points to a specific location within the dataset, indicating where to start fetching the next set of results. To get the first page, set the
cursorparameter tonull.
Implementing Cursor Pagination
Request Parameters
When implementing cursor pagination, you'll need to specify the following request parameters:
per_page: An integer specifying the maximum number of items to return in a single response. This parameter is optional, and if not provided, a default limit of 100 will be used. The value cannot exceed 100.cursor: A token or identifier that points to a specific location within the dataset, indicating where to start fetching the next set of results. To get the first page, set this parameter tonull.
Response Format
The API response should include the following elements:
data: An array containing the paginated data for the current page.links: An object containing links to navigate through the pages, including thenextlink, which provides the URL for the next page.meta: An object providing additional metadata, including thenext_cursor, which is the cursor for the next page.
Here's an example response format:
{
"data": [/* Array of paginated data */],
"links": {
"first": null,
"last": null,
"prev": null,
"next": "https://api.example.com/resource?page=2&cursor=eyJ1c2Vycy5pZCI6MiwiX3BvaW50c1RvTmV4dEl0ZW1zIjp0cnVlfQ"
},
"meta": {
"path": "https://api.example.com/resource",
"per_page": 2,
"next_cursor": "eyJ1c2Vycy5pZCI6MiwiX3BvaW50c1RvTmV4dEl0ZW1zIjp0cnVlfQ",
"prev_cursor": null
}
}
Examples
Requesting the First Page
To request the first page of data, make a GET request to the API endpoint while setting the cursor parameter to null and specifying the desired per_page:
curl --location 'https://api.example.com/resource?per_page=2&cursor=null' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer ExampleToken'
Requesting Subsequent Pages
To request the next page of data, use the next_cursor value obtained from the meta object in the previous response.
curl --location 'https://api.example.com/resource?page=2&cursor=eyJ1c2Vycy5pZCI6MiwiX3BvaW50c1RvTmV4dEl0ZW1zIjp0cnVlfQ' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer ExampleToken'
Handling the End of Results
When you receive a response with a next_cursor that is null or not provided, it indicates that no more pages are available, and you've reached the end of the results. You can stop making further pagination requests at this point, as there is no more data to retrieve.
