How to Total Number of some kind of Resource using the API

Keith Weaver Updated by Keith Weaver

In this tutorial, we will count the total number of resource (such as orders, products, prices, etc.). We will do this using the API. depending on the resource and your commerce type (buyer vs seller), you will need to find the appropriate endpoint.

We will write a basic loop that iterates through each page of results till the number of results is less than the limit passed in. Below is sample Python code for counting the total numbers of products.

import time
import requests # Uses the request library
import sys

def get_results(url str) -> int:
api_key = os.getenv('CONVICTIONAL_API_KEY') # Follow this guide for your API Key: https://developers.convictional.com/reference/introduction#get-your-api-key
headers = {
'Authorization': api_key,
'Content-Type': 'application/json',
}
r = requests.get(url, headers=headers)
if r.status_code != 200: # All non 200 will exit the total program
print ('Request failed', r.status_code, r.text)
sys.exit(1)

return len(r.json()['data']) # The response can be found from the Convictional API docs. https://developers.convictional.com/reference/

def main():
base_url = 'https://api.convictional.com/products'
last_page_found = False
total = 0 # Keep a running total
page = 0 # Convictional starts paging at 0
limit = 10 # Include a maximum of 10 results per request
while not last_page_found:
url = base_url + '?limit=' + str(limit) + '&page=' + str(page)
number_of_results = get_results(url)
total += limit # Must have return 10
if number_of_results < limit:
# End of results reached
last_page_found = True
break
page += 1 # Move onto next page
time.sleep(0.25) # Pause for 0.25 seconds to avoid hitting the rate limiter. You can view more details around rate limiting here: https://developers.convictional.com/docs/rate-limiting

print ('Total number of products is: ' + str(total))


main()

How did we do?

How to Resolve "Your SFTP user requires write permission on your SFTP server."

How to check if you are a buyer or seller on Convictional?

Contact