skip to Main Content

What I need is to get all product IDs that are 'instock' using python.
It looks like this:

wcapi.get('products', params={"per_page": 100, 'stock_status': 'instock', 'tag': '1111'}).json()

This code works, but have max limit 100 per_page, I don’t understand how can I acquire rest of them (about 2k items in stock) and moreover this request returns all info about products, but I need only IDs.

3

Answers


  1. Following the docs, I see that you can pass a page parameter also.

    That makes it pretty straightforward to iterate all pages:

    page = 0
    While True:
      products = wcapi.get('products', params={'per_page': 100, 'stock_status': 'instock', 'tag': '1111', 'page': page}).json()
      # retrieve ids from **products**
      if len(products) == 0: # no more products
        break
      page = page + 1
    

    Edit: Bear in mind that this is going to process per page (in this case 100) products per loop.

    Login or Signup to reply.
  2. There can be several approaches for solving this problem
    You can fetch all products in a single call or in multiple calls according to your use-case

    for example, you want to fetch 2k records in a single call

    products = wcapi.get('products', params={'per_page': 2000, 'stock_status': 'instock', 'tag': '1111', 'page': page}).json()
    

    But the above approach is not good enough as the number of products may vary from time to time, therefore limiting products to be fetched is not a good solution for the long run.

    Hence the better solution is to fetch the product details by multiple calls

    page = 1 #The first page number to loop is page 1 
    products = []
    while True:
        prods = wcapi.get('products', params={'per_page': 100, 'stock_status': 'instock', 'tag': '1111', 'page': page}).json()
        page += 1
        if not prods:
            break
        products.append(prods)
    

    After fetching all the product list you can fetch the product_ids like

    product_ids = [product['id'] for product in products]
    
    Login or Signup to reply.
  3. I used this approach because I have a large quantity of products and kept getting disconnected with a while loop.

    import pandas as pd
    
    def get_product_ids(start, stop):
        my_list = []
        for page in range(start, stop):
            response = wcapi.get("products", params={"per_page": 1, "page": page}).json()[0]
            print(f"Page: {page}", end='r')
            my_list.append(response['id'])
            df = pd.DataFrame({"Product_ids": my_list})
            df.to_csv(f'WooCommerce_product_ids_{stop}.csv', index=False)
    
    get_product_ids(start=22001, stop=23001)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search