How to get product ID from Shopify Python API

I created one private purchase app. Which can get almost all the information with the product ID. But I need one option to get the product id of all products in a store with an API. I tried below option

shopify.Product.find()

      

but it only shows the first 50 products. But my store has over 2.4 thousand products.

+4


source to share


2 answers


Shopify returns broken responses for resource lists. The default is the number of resources per page 50

, and the default is 1

. So your request is equivalent to the following:

shopify.Product.find(limit=50, page=1)

      

Shopify lets you increase the per page limit to 250. Here's the helper function I use to get the entire given resource:

def get_all_resources(resource, **kwargs):
    resource_count = resource.count(**kwargs)
    resources = []
    if resource_count > 0:
        for page in range(1, ((resource_count-1) // 250) + 2):
            kwargs.update({"limit" : 250, "page" : page})
            resources.extend(resource.find(**kwargs))
    return resources

      

You use it like this:



products = get_all_resources(shopify.Product)

      

You can even pass parameters. Your question is asking specifically for the product ID, if you restrict the request to only returning IDs it will be much, much faster (since it shouldn't pull in any of the product variants):

product_ids = get_all_resources(shopify.Product, fields="id")

      

Note that if you have 2.4k products this may take a while!

Documentation: https://help.shopify.com/api/reference/product

+15


source


I thought this might be helpful:



def get_products():
    """
    Returns a list of all products in form of response JSON
    from Shopify API endpoint connected to storefront.

    * Note: Shopify API allows 250 pruducts per call.

    :return:
        product_list (list):    List containing all product response
                                JSONs from Shopify API.
    """

    products = []
    is_remaining = True
    i = 1
    while is_remaining:

        if i == 1:
            params = {
                "limit": 250,
                "page": i
            }

            response = requests.get(
                "{}/products.json".format(SHOPIFY_ENDPOINT),
                params=params
            )

            products.append(response.json()['products'])
            i += 1

        elif len(products[i-2]) % 250 == 0:
            params = {
                "limit": 250,
                "page": i
            }

            response = requests.get(
                "{}/products.json".format(SHOPIFY_ENDPOINT),
                params=params
            )

            products.append(response.json()['products'])
            i += 1

        else:
            is_remaining = False

    products = [products[i][j]
        for i in range(0, len(products))
        for j in range(0, len(products[i]))
    ]

    return products

      

0


source







All Articles