Working at my internship, one of my tasks was to use Shopify’s API to bring down inventory from a partner vendor’s Shopify site to post it onto our marketplace.
There was a few considerations in doing that, which I will explore deeper further on. For one, we weren’t just grabbing every product from the vendor site to put on our site, as it had to match what we had the capacity to sell. Second, it was important to keep constantly changing variables like inventory quantity and price up to date. We decided to do this by running a CRON job that would poll our vendor site(s) for that information and update it accordingly.
The current language we’re working is Python, so I’ll be using the Requests library to make calls.
We had first started off using the REST API, specifically focusing on grabbing all the products using a simple GET request:
response = requests.get(shopify_url, auth=(AUTH, AUTH))
What this would give us, is a whole list of products from a vendor’s site which we then would need to filter against brand (for example “only Apple products”) and product (”only iPhones”). It took 3 passes on the original response (which would be a pretty large JSON file) to get it down to the information that we needed.
To update a product, we would need the sku, inventory quantity, and price. That would be an object looking like this:
{
inventoryQuantity: 10,
sku: "EXAMPLE-SKU",
price: "1.00"
}
Once we had an array of these objects, we’d iterate through each one to update the corresponding variant. (Note: us doing it this way highlights a few flaws in how we’re keeping track of products / variants as there would have been ways to take advantage of the Inventory → Product → Variant hierarchy that Shopify has been using.)
This process was inefficient due to the extra logic needed to filter and parse the JSON response, as the call to the API returned a lot of unnecessary information. This is where GraphQL came in!
One main benefit of GraphQL is being able to query specific data from an API- and I recognized that this would be a great optimization for what we were trying to do. We were also able to update data using mutations, which would ensure proper data typing.
Queries/mutations are done with a POST request to the Shopify GraphQL API. Using cursors to paginate the data, the query to grab exactly what we needed- Apple iPhones and iPads looked like this: