0
votes

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.

2

2 Answers

1
votes

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.

-1
votes

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]