how to create cursor based pagination in shopify rest api using php
We are going to how to create cursor based pagination in Shopify rest API using PHP. recently Shopify page-based pagination replaced by cursor-based pagination across multiple REST endpoints.
REST endpoints support cursor-based pagination. When you send a request to one of these endpoints, the response body returns the first page of results, and a response header returns links to the next page and the previous page of results (if applicable). You can use the links in the response header to iterate through the pages of results.
The link header includes a rel parameter, where relation-types describes the relation of the linked page to the current page of results, this value can either be previous or next.
The link header URL includes three parameters like page_info, limit, and fields.
You can see below the following syntax.
1 2 3 4 5 | //next <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, //previous <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}" |
here, we are getting header response using PHP curl in the below example. if you want to display direct header then it’s not displayed directly. for that, we have to pass the “CURLOPT_HEADERFUNCTION” and after then we can get a header response. so you can see our example code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?php $items_per_page = 50; $next_page = ''; $last_page = false; while(!$last_page) { $url = 'https://{username}:{password}@{shop}.myshopify.com/admin/api/2020-01/product.json?limit=' . $items_per_page . $next_page; // . '&fields='; $curl = curl_init(); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers) { $len = strlen($header); $header = explode(':', $header, 2); if (count($header) >= 2) { $headers[strtolower(trim($header[0]))] = trim($header[1]); } return $len; }); $result = curl_exec($curl); curl_close($curl); if(isset($headers['link'])) { $links = explode(',', $headers['link']); foreach($links as $link) { if(strpos($link, 'rel="next"')) { preg_match('~<(.*?)>~', $link, $next); $url_components = parse_url($next[1]); parse_str($url_components['query'], $params); echo $next_page = '&page_info=' . $params['page_info']; } else { $last_page = true; } } } else { $last_page = true; // if missing "link" parameter - there's only one page of results = last_page } $source_array = json_decode($result, true); } echo "<pre>"; print_r($source_array); echo "</pre>"; ?> |
if you want more information regarding pagination then you can refer below Link Url.
Make paginated requests to the REST Admin API