Call Shopify Cursor Based Pagination from PHP Client

Call Shopify API for Cursor Based Pagination

Shopify API for Cursor Based Pagination

Today in this simple tutorial we will see how to call shopify cursor based pagination from the PHP client. Cursor-based pagination is supported only in version 2019-07 of the API and above. It replaces page-based pagination for the endpoints listed below, for documentation on the new Shopify pagination, you can see the link: https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api.

As we can see from the shopify link just above the link header it will have the structure as below.

#...
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
#...

So the idea is to get this header from the http response for the entity to be paged.
Then to retrieve all the products/orders or other pageable entities, iterate until the response header contains the string rel = “next”.
Each call can return an x number of entities between 0 and 250, a specified limit, we will use 250 as the limit.
The PHP client that we used to perform the Shopify API call is Guzzle, but it can also be implemented using simply the PHP cURLs.
In the snippet below that makes the Guzzle call, will be retur an associative array with the json [“response”] and the header [“headers”] of the http response.

    /**
     * Guzzle Client call.
     * @param $method , type of call.
     * @param $url , endpoint to call.
     * @return array|null, associative array with response and headers.
     */
    private function callServer($method, $url)
    {
        $request = $this->client->createRequest($method, $url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'X-Shopify-Access-Token' => $this->password
            ]
        ]);
 
        $result = null;
        try {
            $response = $this->client->send($request);
            $result = array(
                "headers" => $response->getHeaders(),
                "response" => json_decode($response->getBody(), true)
            );
            return $result;
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            $status = $e->getResponse()->getStatusCode();
            $content = $e->getResponse()->getBody();
            return $result;
        }
    }

It also shows the relative paging method based on the cursor that in the do while loop, iterate as long as in the associative response array we have the string rel=”next”.

private function retrieveCursorResults($methodUri, $entitiesObj)
    {ap
        $results = [];
        $operator = '?';
        if (strpos($methodUri, $operator) > 0)
            $operator = '&';
        $methodUri .= $operator . "limit=250";
        do {
            $result = $this->callServer("GET", $methodUri);
            if (is_null($result)) {
                throw new Exception('Error during cursor retrieve for entity: ' . $entitiesObj);
            } else if (!is_null($result) && count($result["response"][$entitiesObj]) > 0) {
                $results = array_merge($results, $result["response"][$entitiesObj]);
            }
            $methodUri = null;
            if (!is_null($result["headers"]) && isset($result["headers"]["Link"]) && count($result["headers"]["Link"]) == 1) {
                $link = $result["headers"]["Link"][0];
                if(strlen($link) > 0 && strpos($result["headers"]["Link"][0], '>; rel="next"') > 0){
                    $methodUri = trim(substr($result["headers"]["Link"][0], 1, strpos($result["headers"]["Link"][0], '>; rel="next"') - 1));
                }
            }
        } while (!is_null($methodUri) && strlen($methodUri) > 0);
        return $results;
    }

The trick is all in the if:

            $methodUri = null;
            if (!is_null($result["headers"]) && isset($result["headers"]["Link"]) && count($result["headers"]["Link"]) == 1) {
                $link = $result["headers"]["Link"][0];
                if(strlen($link) > 0 && strpos($result["headers"]["Link"][0], '>; rel="next"') > 0){
                    $methodUri = trim(substr($result["headers"]["Link"][0], 1, strpos($result["headers"]["Link"][0], '>; rel="next"') - 1));
                }
            }

Shopify Cursor pagination, I’m not afraid of you ­čÖé

Call Shopify Cursor Based Pagination from PHP Client ultima modidfica: 2020-07-20T09:04:31+02:00 da Gianluca Di Vincenzo
Posted in: PHP

By on 20 Luglio 2020

Tagged: , , , , , ,