How to List All Sales Orders in Zoho Inventory with Pagination
Introduction:
While working with the Zoho Inventory API, I encountered the limitation of retrieving only 200 records per API call. To overcome this, I implemented pagination by tweaking a solution initially built for Zoho CRM. Below is the solution I used to fetch all sales orders, which can be adapted for other modules (Invoices, Packages, etc.).
Problem:
The Zoho Inventory API has a limit of 200 records per API call, which makes it challenging to retrieve a large dataset like all sales orders. This script helps by implementing pagination and recursively fetching data page by page.
Solution:
Here is the code I used. It loops through a list of page numbers and accumulates all records until no further pages are available:
- // *******
- // Zoho Inventory API Pagination for Listing All Sales Orders
- // *******
- // CONFIG: Organization ID
- organizationId = "*****";
- // CONFIG: Name of Zoho Inventory module (SalesOrders, Packages, Invoices, etc.)
- zohoInventoryModule = "salesorders";
- // CONFIG: Number of results to return per page. DO NOT exceed the per_page limit of your API, or this function will not perform correctly.
- perPageLimit = 200;
- // List of page numbers. This should start with '1' and be much longer than the expected number of pages.
- pageIterationList = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
- // List to accumulate all records
- allRecords = List();
- // The 'while' condition for evaluation. While this is 'false', the API requests will continue.
- iterationComplete = false;
- // Loop over each page in the page list
- for each page in pageIterationList
- {
- // Evaluate whether 'while' condition is satisfied
- if(iterationComplete == false)
- {
- // CONFIG: Set the param for OrganizationId if user is set in multiple Organizations
- params = Map();
- params.put("organization_id",organizationId);
-
- // Get records from Zoho Inventory API.
- // CONFIG: Name of Zoho Inventory API Connection
- response = invokeurl
- [
- url :"https://www.zohoapis.eu/inventory/v1/" + zohoInventoryModule + "?page=" + page + "&per_page=" + perPageLimit
- type :GET
- parameters:params
- connection:"zohoinventoryfullcon"
- ];
- // Get records from API response. Add them to allRecords list.
- records = response.get("salesorders");
- allRecords.addAll(records);
- // Update 'while' condition status
- if(response.get("page_context").get("has_more_page") == false)
- {
- iterationComplete = true;
- }
- }
- }
- // Check for correctness
- info "Number of Records: " + allRecords.size();