How to fetch all products from Shopify in a single query using GraphQL

I’ve had a few projects now where I’ve had to sync up inventories in Shopify with some external database that was their source of truth for inventory values.

So essentially I would need to

  • Download all the products from Shopify for a store
  • Iterate through them all comparing the inventory value reported in Shopify with the inventory value reported in their external database.

Previously there was no easy way to simply fetch all products if the store has more than 250 products. The REST API from Shopify has a limit of 250 for retrieving a list of products.

But there is a way to perform a bulk query using GraphQL with the Admin API.

The steps are as follows:

  1. Create a subscription with Shopify so that when they finish compiling all the products, they have a URL to post that data to. See create-subscription.js
  2. Submit a bulk query to Shopify so they can compile all the products together. See submit-query.js
  3. Code up the endpoint that you’ve subscribed to with Shopify when the bulk operation completes with compiling all your products. Shopify will first send a payload that includes a key in the object called admin_graphql_api_id. You can use that key to query for the URL that will have all the data (in this case all our products). Then you can download the data from that URL, and process the data however you like. See get-url-with-data.js

The data will be returned as JSONL. This is JSON but broken up on one line at a time. For example, it might look like this…

{"id":"gid:\/\/shopify\/Product\/12345678","title":"Pavé Evil Eye Bracelet"}
{"title":"Silver, White and Blue Diamond","inventoryQuantity":23,"id":"gid:\/\/shopify\/ProductVariant\/5555555","sku":"207278","__parentId":"gid:\/\/shopify\/Product\/12345678"}
{"id":"gid:\/\/shopify\/Product\/44444444","title":"Pavé Evil Eye Bracelet"}

I found the best way to process the JSONL file is to first figure out what you want from that data exactly. I ended up building a JavaScript object from it, so I could reference it when comparing inventory values with an external database.

Leave a Reply

Your email address will not be published.