Skip to content

Instantly share code, notes, and snippets.

@rseabrook
Created October 16, 2019 19:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rseabrook/4d653e2a9af23791919c84dc8c905994 to your computer and use it in GitHub Desktop.
Save rseabrook/4d653e2a9af23791919c84dc8c905994 to your computer and use it in GitHub Desktop.
How to iterate over all products using the Python Shopify API wrapper

How to iterate over Shopify API results

Shopify switched their API to "cursor-based pagination" in July of 2019. This eliminated the page parameter that made it simple and obvious how to get multiple pages of results.

The Python wrapper for the Shopify API actually makes it quite difficult to page through results now. The API responds with next and previous URLs via the response headers that can be used to retrieve different pages of results, but the python wrapper actually drops these headers. There is a pull request waiting to be merged that will give access to convenient next and previous methods. In the meantime, maybe this will be useful to someone else...

Requirements

  • Shopify private app with API key and password
import shopify

SHOP_HANDLE = '<INSERT SHOP HANDLE>'
API_KEY = '<INSERT API KEY>'
PASSWORD = '<INSERT APP PASSWORD>'
API_VERSION = '2019-07'


def get_all_products(limit=100):
    get_next_page = True
    since_id = 0
    while get_next_page:
        products = shopify.Product.find(since_id=since_id, limit=limit)

        for product in products:
            yield product
            since_id = product.id

        if len(products) < limit:
            get_next_page = False

def main():
    shop_url = "https://{}.myshopify.com/admin/api/{}".format(SHOP_HANDLE, API_VERSION)
    shopify.ShopifyResource.set_site(shop_url)
    shopify.ShopifyResource.set_user(API_KEY)
    shopify.ShopifyResource.set_password(PASSWORD)
    
    for product in get_all_products():
        # Do something with product
        print(product.title)

if __name__ == "__main__":
    main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment