user11736353
user11736353

Reputation: 87

Rate limit Shopify API calls in Ruby

I am using Shopify's shopify_api gem in Ruby.

I am updating each products cost and price from an external source however I am hitting the API limits and receiving 429 Too Many Requests (https://help.shopify.com/en/api/reference/rest-admin-api-rate-limits).

How can I edit the below to respect the API limits?

I would rather use the data supplied in X-Shopify-Shop-Api-Call-Limit and Retry-After rather than adding a fixed sleep.

products = ShopifyAPI::Product.find(:all, :params => {:limit => limit})

products.each do |product|
                variant = ShopifyAPI::Variant.find(product.variants.first.id)

                variant.price = price
                variant.save

                inventoryitem = ShopifyAPI::InventoryItem.find(product.variants.first.inventory_item_id)

                inventoryitem.cost = cost
                inventoryitem.save
        end
end

Upvotes: 5

Views: 1260

Answers (3)

Dumb E.
Dumb E.

Reputation: 46

I would rather use the data supplied in X-Shopify-Shop-Api-Call-Limit and Retry-After rather than adding a fixed sleep.

The Shopify API Retry gem does this. It looks to Retry-After header but does use fixed sleep. No way around sleeping. How else to wait?

It does not do any "monkey patching". This is good. Monkey patching likely will cause problem at some point.

To use with your code

products = ShopifyAPIRetry.retry { ShopifyAPI::Product.find(:all, :params => {:limit => limit}) }
products.each do |product|
  variant = ShopifyAPIRetry.retry { ShopifyAPI::Variant.find(product.variants.first.id) }

  variant.price = price
  ShopifyAPIRetry.retry { variant.save }

  inventoryitem = ShopifyAPIRetry.retry { ShopifyAPI::InventoryItem.find(product.variants.first.inventory_item_id) }

  inventoryitem.cost = cost
  ShopifyAPIRetry.retry { inventoryitem.save }
end

Having to call retry everywhere is not that nice. You could possibly consolidate some places into single call.

Upvotes: 0

claasz
claasz

Reputation: 2134

There's a gem from Shopify itself to help with rate limiting: https://github.com/Shopify/limiter.

Upvotes: 2

David Lazar
David Lazar

Reputation: 11427

The simplest approach is to Monkeypatch ActiveResource. Here is a repo that does all the work for you.

https://github.com/mikeyhew/shopify_api_mixins

Upvotes: 0

Related Questions