Kaizen #92 - Bulk Read in PHP SDK

Kaizen #92 - Bulk Read in PHP SDK

Heya! Welcome back to the PHP SDK fold in our Kaizen series.

In this post, we will explore how to use bulk read APIs and how to structure the criteria format for different field data types in PHP SDK based on v4 APIs. This will ease your process of handling large volumes of data in an efficient and streamlined manner. 

What does Bulk Read API do?

The Bulk Read API helps you to fetch large volumes of data that meet specific criteria in a single request. Unlike the GET Records API , which has a limitation of 200 records per call, the Bulk Read API allows you to extract bulk data, 200k records, for data synchronisation purposes. This prevents the need for you to fire multiple API calls which can easily drain your daily credits.

This Bulk Read is asynchronous, thus the result for your request will not be available immediately. So, you will have to either poll the bulk read job status API to know the status or specify a callback URL for Zoho CRM to send notifications regarding the process. 

The CRM system processes your request and returns the results in either a CSV or ICS (for Meetings/Events module) zipped file. To download your result, use the job ID given in the response of bulk read job API .

This entire process can be wrapped into three stages as given below, 
  • Creating a Bulk Read Job 
  • Checking the status of a Bulk Read Job
  • Downloading the CSV/ICS data zip

Create a Bulk Read Job

1. Adding Callback URL

To get notified of the progress and results of the bulk read job, add a callback URL to the request body using the following format. 
$requestWrapper = new RequestWrapper();

$callbackVar = new CallBack();

$callbackVar->setUrl(" your_callback_url ");

$callbackVar->setMethod(new Choice("post"));

$requestWrapper->setCallback($callbackVar);
The method for callback URL is typically set to POST as it helps the client to send the required data along with the url to handle the callback appropriately.

2. Structuring a Query

A query comprises multiple parameters such as your desired module, fields, custom view ID, page value, file-type and criteria.

A criterion is typically a filter/condition used in a query to narrow down the data to your desired set of records. Criteria can include one or more conditions and you can combine them using group operators like 'and' and 'or' to create more complex filtering logic. 

Each condition in the criteria comprises three components.
  • Field - It refers to the field API name of the record, which you want to use for filtering purpose.
  • Comparator - It determines how the value of the specified field has to be evaluated.
  • Value - It represents the value of the field against which the record has to be evaluated.
This helps you to retrieve only the relevant records, thereby optimising the performance and reducing the amount of data transferred.

To enhance the understanding of how to structure a criterion, it is necessary to address these group operators and comparators before delving into it.

Group Operators 

Group Operators are used to perform logical operations on multiple conditions within a query. They help you in grouping multiple conditions together to create complex search criteria.The possible group operators are 'and' and 'or'.
  • and - It specifies that all conditions within the group must be satisfied for a record to be included in the query result.
  • or - It specifies that any of the conditions within the group can be satisfied for a record to be included in the query result.
These operators provide flexibility in constructing queries and retrieve the desired set of records from your CRM system with ease.

Comparators

Comparators are used in a query condition to specify the type of comparison that should be performed between a field and a value. They define the relationship between the field and the value and determine how the records are filtered. Refer to this help document to find the possible comparators with their field datatypes. 

An example of each datatype is given in PHP for your better understanding. 
Data Type
Example
  Number

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("Amount");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("greater_than"));
$conditionVar->setValue(10000);

  Multi-select 

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("owner");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("in"));
$owner = ["5545974393001", "5545974393011"]
$conditionVar->setValue($owner);

  DateTime                                   

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field->setAPIName("Created_Time");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("between"));
$createdTime = [date_create("2023-05-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())), date_create("2023-06-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get()))];
$conditionVar->setValue($createdTime);

  Boolean

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("Email_Opt_Out");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("equal"));
$conditionVar->setValue(false);

  Lookup

$conditionVar = new Criteria();
$field = new MinifiedFields();
$field ->setAPIName("owner.last_name");
$conditionVar>setField($field);
$conditionVar->setComparator(new Choice("equal"));
$conditionVar->setValue("Boyle");

Structuring Simple Criteria

Below is a query format with a simple criterion of two conditions to filter your records from the given module. 

$criteriaVar = new Criteria();

$criteriaVar->setGroupOperator(new Choice("operatorValue"));

$conditionVar1 = new Criteria();

$fieldVar = new MinifiedFields();

$fieldVar->setAPIName("Field_API_Name");

$conditionVar1->setField($fieldVar);

$conditionVar1->setComparator(new Choice("comparatorValue"));

$conditionVar1->setValue("Field_Value");

$conditionVar2 = new Criteria();

$field = new MinifiedFields();

$field->setAPIName("Field_API_Name");

$conditionVar2->setField($fieldVar);

$conditionVar2->setComparator(new Choice("comparatorValue"));

$conditionVar2->setValue("Field_Value");

$criteriaVar->setGroup([$conditionVar1,$conditionVar2]);

$query->setCriteria($criteriaVar);

$requestWrapper->setQuery($query);

In the above format, the group operator is used for two different conditions.

Following is the json format of this simple criteria.
{
    "query": {
        "criteria": {
            "group_operator": "operatorValue",
            "group": [
                {
                    "comparator": "comparatorValue",
                    "field": {
                        "api_name": "Field_API_Name"
                    },
                    "value": "Field_Value"
                },
                {
                    "comparator": "comparatorValue",
                    "field": {
                        "api_name": "Field_API_Name"
                    },
                    "value": "Field_Value"
                }
            ]
        }
    }
}

Structuring Complex Criteria

To structure a criterion with four different conditions follow the below format.

//top-level group criteria with 2 different groups comprising of 2 different conditions each

$criteria = new Criteria();

$criteria->setGroupOperator(new Choice("operatorValue"));

//group1 with 2 different conditions

$groupVar1 = new Criteria();

$groupVar1->setGroupOperator(new Choice("operatorValue"));

$conditionVar11 = new Criteria();

$field11 = new MinifiedFields();

$field11->setAPIName("Field_API_Name");

$conditionVar11->setField($field11);

$conditionVar11->setComparator(new Choice("comparatorValue"));

$conditionVar11->setValue("Value");

$conditionVar12 = new Criteria();

$field12 = new MinifiedFields();

$field12->setAPIName("Field_API_Name");

$conditionVar12->setField($field21);

$conditionVar12->setComparator(new Choice("comparatorValue"));

$conditionVar12->setValue("Value");

$groupVar1->setGroup([$conditionVar11, $conditionVar12]);

//group2 with 2 different conditions

$groupVar2 = new Criteria();

$groupVar2->setGroupOperator(new Choice("operatorValue"));

$conditionVar21 = new Criteria();

$field21 = new MinifiedFields();

$field21->setAPIName("Field_API_Name");

$conditionVar21->setField($field21);

$conditionVar21->setComparator(new Choice("comparatorValue"));

$conditionVar21->setValue("Value");

$conditionVar22 = new Criteria();

$field22 = new MinifiedFields();

$field22->setAPIName("Field_API_Name");

$conditionVar22->setField($field22);

$conditionVar22->setComparator(new Choice("comparatorValue"));

$conditionVar22->setValue("Value");

$groupVar2->setGroup([$conditionVar21, $conditionVar22]);

//pushing the groups to the top-level group criteria

$criteria->setGroup([$groupVar1, $groupVar2]);

In the above format, two group variables ($groupVar1 and $groupVar2) are created, each representing a nested group of conditions. Both the groups are further assigned to the top-level group variable ($criteria). 

The json arrangement of the above format is given for your clarity.
{
    "query": {
        "criteria": {
            "group_operator": "operatorValue",
            "group": [
                {
                    "group_operator": "operatorValue",
                    "group": [
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        },
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        }
                    ]
                },
                {
                    "group_operator": "operatorValue",
                    "group": [
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        },
                        {
                            "comparator": "comparatorValue",
                            "field": {
                                "api_name": "Field_API_Name"
                            },
                            "value": "Field_Value"
                        }
                    ]
                }
            ]
        }
     }
}

The default file type is CSV. To bulk read the Events module always prefer the ICS file type. Refer to this resource to fetch the custom view IDs, module and field API names. 

Below is a sample code for creating a bulk read job with compound criteria. The criteria follow this arrangement ((1 and 2) or (3 or 4)) of conditions.

<?php

use com\zoho\crm\api\bulkread\BulkReadOperations;
use com\zoho\crm\api\bulkread\CallBack;
use com\zoho\crm\api\util\Choice;
use com\zoho\crm\api\bulkread\Query;
use com\zoho\crm\api\bulkread\Criteria;
use com\zoho\crm\api\bulkread\RequestWrapper;
use com\zoho\crm\api\modules\MinifiedModule;
use com\zoho\crm\api\fields\MinifiedFields;
require_once "vendor/autoload.php";

class CreateBulkReadJob
{
public static function initialize()
    {
        // Add initialisation code
        // Refer to this article for more help
    }
    public static function createBulkReadJob(string $moduleAPIName)
    {
        $bulkReadOperations = new BulkReadOperations();
        $requestWrapper = new RequestWrapper();
        $callback = new CallBack();
        $callback->setUrl("https://www.callback.com/example");
        $callback->setMethod(new Choice("post"));
        $requestWrapper->setCallback($callback);

        //query
        $query = new Query();
        $module = new MinifiedModule();
        $module->setAPIName($moduleAPIName);
        $query->setModule($module);
        $query->setCvid("34770610087501");
        $query->setFields(["Last_Name"]);
        $query->setPage(1);

        //top-level group criteria with 2 different groups comprising of 2 different conditions each
        $criteria = new Criteria();
        $criteria->setGroupOperator(new Choice("or"));
        $criteriaList = array();

        //group1 with 2 different conditions
        $groupVar1 = new Criteria();
        $groupVar1->setGroupOperator(new Choice("and"));

        $conditionVar11 = new Criteria();
        $field11= new MinifiedFields();
        $field11->setAPIName("Last_Name");
        $conditionVar11->setField($field11);
        $conditionVar11->setComparator(new Choice("equal"));
        $conditionVar11->setValue("Boyle");
        
        $conditionVar12 = new Criteria();
        $field12 = new MinifiedFields();
        $field->setAPIName("Owner");
        $conditionVar12->setField($field12);
        $conditionVar12->setComparator(new Choice("in"));
        $owner = array("5545974000000393001","5545974000000393011");
        $conditionVar12->setValue($owner);
        $groupVar1->setGroup([$conditionVar11, $conditionVar12]);

         //group2 with 2 different conditions
        $groupVar2 = new Criteria();
        $groupVar2->setGroupOperator(new Choice("or"));

        $conditionVar21 = new Criteria();
        $field21 = new MinifiedFields();
        $field21->setAPIName("Company");
        $conditionVar21->setField($field21);
        $conditionVar21->setComparator(new Choice("equal"));
        $conditionVar21->setValue("Morlong Associates");
        
        $conditionVar22 = new Criteria();
        $field22= new MinifiedFields();
        $field22->setAPIName("Created_Time");
        $conditionVar22->setField($field22);
        $conditionVar22->setComparator(new Choice("between"));
        $createdTime = array(date_create("2023-04-15T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())), date_create("2023-06-01T17:58:47+05:30")->setTimezone(new \DateTimeZone(date_default_timezone_get())));
        $conditionVar22->setValue($createdTime);
        $groupVar2->setGroup([$conditionVar21, $conditionVar22]);

         //pushing the groups to the top-level group criteria
        $criteria->setGroup($criteriaList);
        $query->setCriteria($criteria);
        $requestWrapper->setQuery($query);
        // $requestWrapper->setFileType(new Choice("ics")); for Events module
        $response = $bulkReadOperations->createBulkReadJob($requestWrapper);
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
CreateBulkReadJob::initialize();
$moduleAPIName = "Leads";
CreateBulkReadJob::createBulkReadJob($moduleAPIName);
?>

2. Status of a Bulk Read Job

To keep track of the status of your bulk read job, use the id provided in the details section of your bulk read job response. 

Here is a sample code for checking the status of a bulk read job.

<?php

use com\zoho\crm\api\bulkread\BulkReadOperations;

require_once "vendor/autoload.php";

class GetBulkReadJobDetails
{
public static function initialize()        
    {
        // Add initialisation code
        // Refer to this article for more help 
    }

    public static function getBulkReadJobDetails(string $jobId)
    {
        $bulkReadOperations = new BulkReadOperations();
        $response = $bulkReadOperations->getBulkReadJobDetails($jobId);
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
GetBulkReadJobDetails::initialize();
$jobId = "55459743108003";
GetBulkReadJobDetails::getBulkReadJobDetails($jobId);
?>

3. Download Bulk Read Result

To download your bulk read job result, use the job id mentioned in the bulk read job response. Additionally, provide the path of the destination folder where you would like to download the result. The result will be downloaded as a zip file containing CSV/ICS files.
Here is a sample code for downloading a bulk read job result.

<?php

namespace samples\bulkread;

use com\zoho\crm\api\bulkread\BulkReadOperations;

require_once "vendor/autoload.php";

class DownloadResult
{
public static function initialize()
    {
        // Add initialisation code
        // Refer to this article for more help  
    }
    public static function downloadResult(string $jobId, string $destinationFolder)
    {
        $bulkReadOperations = new BulkReadOperations();
        $response = $bulkReadOperations->downloadResult($jobId);
        $streamWrapper = $response->getObject()->getFile();
        fputs(fopen($destinationFolder . "/" . $streamWrapper->getName(), "w"), $streamWrapper->getStream());
        //Add your code to handle the response received in $response
        // For more details, refer here.
    }
}
DownloadResult::initialize();
$jobId = "55459743108003";
$destinationFolder = "/Downloads";
DownloadResult::downloadResult($jobId, $destinationFolder);
?>

We hope you found this post useful and engaging! 

If you have any queries, feel free to drop them in the comments section below or reach out to us directly at support@zohocrm.com. We value your thoughts and eagerly look forward to hearing from you.

Stay tuned for more enriching posts coming your way soon!

Cheers!

    • Recent Topics

    • Filter Page Elements By Selectable Date Range

      I have created a basic Page that will serve as a client dashboard with elements that will provide simple counts & sums of data in reports. There are no reports or forms added to the page, just elements. It currently functions as needed, but shows the
    • Can’t Enter my Notebook is Locked

      I’ve been using Notebook for taking notes at my college for a month and I never signed in and I never established a password. Today I tried to enter the app after the update and it asked me for a password. I need to access to my notes urgently and I can’t
    • Send Email Directly to Channel

      Hi, We are coming from Slack. In Slack each channel has a unique Email address that you can send emails too. I currently forward a specific type of email from my Gmail InBox directly do this channel for Verification Codes so my team doesn't have to ask
    • Secure your external sharing process with OTP Authentication

      For any business, it's crucial to share files externally in a way that is both secure and controlled. Let's say you want to share confidential data with your partners and vendors. You must ensure that only your intended recipients can access the shared
    • Items attribute questions

      Many of my items have attributes, such as size and color. How can I add new fields to the "New Items" screen to capture that in my Purchase Orders, Items, and Sales Order pages? I only see these attribute fields when adding an Item Group. Also, on the
    • Is there a way to search mail for items you haven't yet responded to?

      I'm trying to create a search to show emails that haven't been responded to and that have also been assigned a tag or label. Is there a way to search for the inverse of replied?
    • Zobot and Sales IQ

      What will happen to the Zoho Sales IQ being integrated to the website after creating the Zobot on the website too
    • Subtotals per Header

      Hey, we would like to display subtotals per header in our invoices:
    • upgrade storage

      how to upgrade my storage
    • Linking items from books and subscription

      Linking books and subscription It is a pity that it is not possible to associate with a product an article present in ZohoBooks This would make it possible to manage products composed of a nomenclature of articles of books
    • Add the ability to view number of hours planned for a workorder while in the Dispatch Console

      Hi Zoho, When dispatching a work order through the Dispatch Console, there's currently no way to view the number of planned hours for the service tasks associated with that specific work order. Having to click into the details each time to check planned
    • Uploading Files from uploads api

      I tried uploading the image from the API call but its giving me unauthorized error even i have given valid token in header. After uploading i need that id to pass in create ticket api uploads but its not uploading that file. Please help me out in th
    • Categorize Items with Item Headers

      Hello customers, Did you ever want to classify items based on specific categories to help your customers understand your invoice better? With the new Item Header feature, you can easily categorize items in your invoices and estimates and give them a common title.  Item Headers are available in the Invoices, the Recurring Invoices and the Estimates module. It can be carried forward from estimates to invoices at the time of converting the estimates.  To add an item header: Go to the Estimates, Invoices
    • URLs being masked despite disabling tracking

      Hey, We had disabled click tracking from an email update we are sharing with our users. Despite this, the URL the end user is receiving is masked, and looks like "https://qksyl-cmpzourl.maillist-manage.net/click/1d8e72714515cda6/1d8e72714515ca70" instead
    • Change format of quantity format

      Hi,  I would like to change the qunatity format from 1,00 to 1.  Is this possible?   thanks!
    • square up and Zoho books

      Since we set up the app connection between square up and Zoho books we have realised that when the amounts are getting transferred Zoho is adding VAT again making the numbers 20% more than they should be. We have checked our settings and they VAT/ Tax
    • How to provide Access rights to specific Bank accounts

      We have several bank accounts. I want to provide certain members access to only 2-3 accounts. It appears that when I give permissions, they are for ALL bank accounts. How do I do that?
    • Errors Getting a Bank Transaction

      Using Postman(for testing), I am receiving errors when attempting to get a single bank transaction. I am able to receive the list of bank transactions with https://www.zohoapis.com/books/v3/banktransactions/?organization_id={org_id} but when I try to
    • Subscriptions Plans and CRM Products Integration?

      Is there any way to set up plans and pricing in Zoho Subscriptions and have those available as Products in the CRM? We are trying to set up the CRM and the Products seem to be more geared toward selling products that are not subscription based.  So if we sell annual or monthly contracts which are $10/seat/month, I can set this up as a plan in Subscriptions, but how can I set the same thing up in the CRM for the salespeople to sell/quote? What is the best practice for setting up the CRM Products to
    • Mapping Zoho Subscription Plans and Products to CRM and Books

      We have products that are one time products and subscription products.   1) We would like to have the ability to create an opportunity in CRM that includes both one-time charge products and subscription products.  Currently the only way of creating a subscription product is by defining a "Product->Plan" hierarchy in Zoho Subscription.  It appears that the only SYNC between Subscription and CRM is around contacts and the Product->Plan hierarchy doesn't sync to CRM, thus, you would need a duplicate
    • Zoho People Attendance Module - Split Shifts

      Hello, Our business employs a number of college students who often split their workdays between work hours and class schedules, resulting in split shifts. For example: Employee 1 works 9am to 11:30am and then leaves for class, returning to work at 3pm
    • Bulk update fields based on date

      Hi! I need all the quotes with "Quote Stage" set to "Next Year" to update to "Draft" every January 8 (every year). Can you help?
    • Target for a campaign

      Hi, Hope you can help me. I need to create a report (for a marketing campaign) that combines Deals and Contacts to export all the contacts with closed deals. I can easily do that, what I cannot do is to remove from the target the contacts that have more
    • Zoho Desk + Jira integration - Email notifications and comments posted by administrator instead of real user

      Dear All, I set up the integration under my admin account, and now when users leave comments in Jira (to created tickets in Zoho Desk), the email notifications show that the ‘Administrator’ left a comment, not a real user. The same happens in the ticket
    • Celebrating the power of visuals

      On World Photography Day, we would like to highlight the power of visuals in customer service. Visuals promote learning and understanding in less time. A photograph can rekindle a memory, convey more than words, and give a fresh perspective. How does
    • Customer address in Zoho Bookings

      Hello,  Is it possible to add customer address information to the Zoho bookings appointment screen? Or have it pull that information automatically from the CRM? We are wanting to use this as a field management software but it is difficult to pull the address from multiple sources when it would be ideal to have a clickable address on the appointment screen that opens up the user's maps.  It would also be advantageous for the "list view" to show appointment times instead of just duration and booking
    • Blocking / black listing customers

      Hi, We have a situation, we observed that certain customers are blocking multiple appointments with our advsiors but not showing up. Some of these are repeat offenders. This leads to those service hours getting blocked and not available for genuine customers.
    • Option to block bookings from specific email address or ip adresss in zoho booking

      Sometime few of our client keep booking irrelevant booking service just to resolve their queries and they keep booking it again and again whenever they have queries. Currently its disturbing our current communication process and hierarchy which we have
    • Feature Request: Email Templates for notifications accross all services

      Currently in Zoho Bookings, email notifications (such as booking confirmations, reminders, and cancellations) must be customized individually for each service. This becomes time-consuming and error-prone when managing multiple services that require consistent
    • Allow customers to choose meeting venue and meeting duration on booking page

      My business primarily involves one-to-one meetings with my clients. Given the hybrid-work world we now find ourselves in, these meetings can take several forms (which I think of as the meeting "venue"): In-person Zoom Phone call I currently handle these
    • Approval-based booking with Zoho Creator and Zoho Bookings

      Hi community members, We have developed a workaround for approval-based booking using Zoho Creator and Zoho Bookings! This provides a temporary solution as we work on the native feature, and it's useful for anyone needing an approval workflow when confirming
    • Member Accounts in Related List

      Hi Team, Currently, when a parent account is associated with an account in FSM, there is no related list displaying the associated member accounts under the parent account’s related list section. To view member accounts, I have to manually search using
    • how do i remove a specific Zoho Service from my account

      I no longer need Zoho CRM, ZRM Assist nor ZRM BugTracker. How do I remove them from the list of apps for my account?
    • I Want migarte all invoice details to zoho sheets

      I want to migrate all existing invoice details to Zoho Sheet, and automatically update the sheet whenever a new invoice is created.
    • were can i find my invoices i need this for my accountant

      were can i find my invoices i need this for my accountant, how can i get id direct to my email?
    • ONLY email field not populating Writer fillable document (randomly)

      I have a Zoho Writer fillable document that has pulled all my data from my Zoho Sheets file, EXCEPT the email column. It pulled every data before and after that column with no issues. Screenshots attached. It's not my first time using the app or the feature,
    • My number is marked as spam

      Hello Zoho Mail Support, My phone number was incorrectly flagged as “spam” during sign-up. This is my personal number, and I have not engaged in any spam activities. Kindly review and verify my account so I can proceed with my email setup. Thanks.
    • Personnalisation des paramètres dans Zoho Mail

      Pourquoi cela compte-t-il ? La personnalisation des paramètres dans Zoho Mail permet aux administrateurs de configurer l’environnement de messagerie en fonction des besoins spécifiques de leur organisation. Que ce soit pour alléger l’interface pour certaines
    • How To Save Data Into Zoho CRM Sandbox

      Hi Community, I want to save data into my zoho sandbox , for this I am using this api endpoint - https://www.zohoapis.com/crm/v8/Patients but I am getting this error - { "success": false, "message": "Zoho API request failed", "error": { "code": "INVALID_MODULE",
    • Automate pushing Zoho CRM backups into Zoho WorkDrive

      Through our Zoho One subscription we have both Zoho CRM and Zoho WorkDrive. We have regular backups setup in Zoho CRM. Once the backup is created, we are notified. Since we want to keep these backups for more than 7 days, we manually download them. They
    • Next Page