woocommerce / wc-api-python

A Python wrapper for the WooCommerce API.
https://pypi.org/project/WooCommerce/
MIT License
213 stars 113 forks source link

Pagination support #89

Open geri777 opened 1 year ago

geri777 commented 1 year ago

Currently this API implementation does not offer a pagination feature. https://woocommerce.github.io/woocommerce-rest-api-docs/#pagination Would it be possible to perform pagination inside your API class? - And recursively perform the requests until the last page is received?

aapjeisbaas commented 1 year ago

I just needed this and a wrote a little pagination inside a product fetch function:

def all_products(wcapi):
    r = wcapi.get("products")
    if r.status_code != 200:
        print("error fetching products")
        return

    # create list with first page results
    products = r.json()

    # pagination
    while 'next' in r.links and r.status_code == 200:
       r = wcapi.get(r.links['next']['url'].split("wp-json/wc/v3/")[1])
       products += r.json()

    if r.status_code > 200:
        print(f"Got an unexpected http response: {r.status_code}, returning what I can...")

    return products

Use it for inspiration maybe someone want to implement this into the package as a wrapper.

Explanation: The requests object returned from wcapi.get has a links object which represents the Link return header and the named links that were in there. The links object is an empty dict if there are no link headers defined.

>>> import requests
>>> r = requests.get("https://aapjeisbaas.nl)
>>> type(r.links)
<class 'dict'>
>>> r.links
{}
>>> 

sidenote: requests also has a r.next but it is not implemented to support this type of pagination.