Kaizen 172 Leveraging the 'crmAPIResponse' object in Queries

Kaizen 172 Leveraging the 'crmAPIResponse' object in Queries



Hello everyone!
Welcome back to another week of Kaizen!

We released the Queries feature sometime back and hope you have tried it out.

A little gist about this feature before we move on to our post.

Zoho CRM's Queries feature enables dynamic data retrieval from both CRM modules and external services, facilitating seamless integration and informed decision-making.

Key Components

  • Sources: Pre-configured sources like Modules and COQL are available, with the option to add custom sources via REST APIs.
  • Queries: Fetch data by selecting modules, writing COQL statements, or specifying REST API endpoints, headers, and parameters.
  • Variables: Incorporate variables in criteria, COQL statements, and endpoints to pass dynamic values during execution.
  • Schema: Auto-generated schemas define the structure of query responses, with editable paths, field types, and labels for customization.
  • Serializer: Utilize JavaScript to manipulate and customize query responses, ensuring data is in the desired format for further processing.

Types of Queries

  • Modules: Retrieve records by selecting specific modules and fields, applying conditions to filter data as needed.
  • COQL (CRM Object Query Language): Write SQL-like queries to fetch data, supporting complex operations like joins and aggregations.
  • REST API: Fetch data from external services by specifying endpoints, headers, parameters, and connections.

With the Queries feature, you can efficiently access and display relevant data within Zoho CRM, enhancing workflow efficiency and decision-making capabilities.

A little insight into Functions before we dive into today's Kaizen!

Functions, Queries, you get the connection, right? Read on!

Many of us use Functions in Zoho CRM extensively to perform our business logic and customize the way things work in Zoho CRM. You can use Functions in blueprints, workflows, Circuits etc.

Let's say you have a function that gets the employee records from the Employees module. Technically, the function executes an API call or an integration task, and gives a response.

The response can be a string or map(JSON), depending on how the function is written and where it is used. Since functions can be used in many places, the same response format may not be the right one to be used in a circuit or a workflow.

This is where the genie 'crmAPIResponse' object comes into picture!

The power of the 'crmAPIResponse' object

The crmAPIResponse object to be returned in the CRM function should encapsulate the response in a way that it can be used in Queries, Circuit, workflow etc. The details needed are encapsulated as a map. It should include details like crmStatusCode, status, message, body in order to construct the desired format for handling data and customizing the error handling logic.

Let's consider the following example function where we use the getRecordByID integration task.

The response of the integration task contains all the fields in that module, but we want only certain parts of the response JSON and also add custom error messages, to be used in other components like Queries, Circuits, etc,.

Here is the code.
{
leadId = "3652397000018025772"; // Replace with a valid Lead ID

// Initialize customAPIResponse map
customAPIResponse = map();

// Fetch lead details
crmResponse = zoho.crm.getRecordById("Leads", leadId);

// Log the raw response for debugging
info "CRM API Raw Response: " + crmResponse;

// Validate and process the response to include only the required fields
if (crmResponse != null && crmResponse.containsKey("id"))
{
// Extract required fields
filteredData = map();
filteredData.put("id", crmResponse.get("id"));
filteredData.put("Last_Name", crmResponse.get("Last_Name"));
filteredData.put("Email", crmResponse.get("Email"));

customAPIResponse.put("crmStatusCode", 200);
customAPIResponse.put("status", "success");
customAPIResponse.put("message", "Lead data retrieved successfully.");
customAPIResponse.put("body", filteredData); // Include only filtered data
}
else
{
customAPIResponse.put("crmStatusCode", null);
customAPIResponse.put("status", "error");
customAPIResponse.put("message", "Invalid or null response from Zoho CRM API.");
customAPIResponse.put("body", null);
}

// Return the customAPIResponse
return {"crmAPIResponse": customAPIResponse};

}


Here, you can see that we have parsed the response of the integration task to get the Last_Name, Email, and record ID using the crmResponse.get("field_API_name") statement and constructed the customAPIresponse object using the customAPIResponse.put("key", "value") statement.
The statement return {"crmAPIResponse": customAPIResponse}; returns the response body as depicted in the previous statements.

Response to the info "CRM API Raw Response: " + crmResponse; statement
"CRM API Raw Response: {"Owner":{"name":"Patricia Boyle","id":"3652397000000186017","email":"p.boyle@zylker.com"},"$field_states":null,..}}}


Response of the return {"crmAPIResponse": customAPIResponse}; statement

{
    "crmAPIResponse": {
        "crmStatusCode": 200,
        "status": "success",
        "message": "Lead data retrieved successfully.",
        "body": {
            "id": "3652397000018025772",
            "Last_Name": "Math",
            "Email": "math@gmail.com"
        }
    }
}

Error response

{
    "crmAPIResponse": {
        "crmStatusCode": null,
        "status": "error",
        "message": "Invalid or null response from Zoho CRM API.",
        "body": null
    }
}

You can see that we have used the crmAPIResponse object to get only the required keys from the response and constructed a much simpler response.
Refer to our help page on Response Object for more details.

Finally, to today's Kaizen!

We've established that you can use the crmAPIResponse object to construct responses in a way that's suitable to be consumed at another place like a circuit or a workflow.
We also know that Queries allows you to have sources of the REST API type to fetch data from various sources. This means that you can have a standalone function that is enabled as a REST API as a source in Queries.

Let's see an example.
There is a simple function that uses the getRecords integration task to get the records from the Employees module.
I have used the crmAPIresponse object to construct a response as shown in the following code.

string standalone.getRecords()
{
result = zoho.crm.getRecords("Employees");
response = Map();
response.put("status_code",200);
response.put("body",{"code":"success","details":result,"message":"function executed successfully"});
return {"crmAPIResponse":response};
}

The response of this function is a string in the crmAPIResponse object as shown in this image.


  1. Save this function and enable REST API.

  2. You can see that the domain is https://www.zohoapis.com. To be able to use this in a Query, register this domain in Trusted Domain.

  3. To create a REST API type source, you must add the source. Go to Setup > Developer Hub > Queries > Sources tab.
  4. Click Add Source and give the details like the name, base URL, headers, and parameters under the Information section.

  5. Click Save.
  6. Go to the Queries tab and click Add Query.
  7. For Source, choose the source you just added.
  8. Under Information, enter the name, API name of the query.
  9. For the endpoint, enter the API Key URL of the function.

  10. Enter the parameter name and values in the Parameter field.
  11. Click Add Serializer if you want to serialize the response. In this example, I have serialized the response to include only the Name, Email, and Position fields in the output. The result contains the 'body' object that we returned in the crmAPIResponse object of the function.

  12. Click Save to save the serialization.
  13. Click Next to view the schema of the query. Make changes as required.
  14. Save the query.
You can now use this query in Canvas or associate it with Kiosk to solve your business needs.

Let us see how the crmAPIResponse object in the function affects the response of the query.

Query with the function without crmAPIResponse:

Let's consider that the function getRecords() does not use the crmAPIResponse object. In that case, the function returns a response that is a string. This response string cannot be serialized or used elsewhere.


Schema of the query without crmAPIResponse:


Query with the function with crmAPIResponse and serialization:

The same getRecords() function that uses the crmAPIResponse object allows you to construct the response as JSON. You can serialize this response easily and use it in a circuit, query, workflow etc.


You can see here that the response is now a JSON.

Schema of the query with crmAPIResponse:



In conclusion, you can use the crmAPIResponse object in Functions to construct the desired response and use the REST API-enabled function as a source in Queries.
Leveraging the advantage of the crmAPIResponse object in functions and using it in Queries increases the prospect of solving many more business cases easily and customize more efficiently.

We hope you liked this post and found it useful. Let us know your thoughts in the comments.
If you'd like us to cover any other topic in this series, feel free to comment or reach us at support@zohocrm.com.



Cheers!

------------------------------------------------------------------------------------------------------------------------------------------------
Info
More enhancements in the COQL API are now live in Zoho CRM API Version 7. Check out the V7 Changelog for detailed information on these updates.






    Access your files securely from anywhere



                          Zoho Developer Community




                                                  • Desk Community Learning Series


                                                  • Digest


                                                  • Functions


                                                  • Meetups


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner


                                                  • Word of the Day


                                                  • Ask the Experts





                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner





                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources


                                                                                              Zoho Writer Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ










                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • HTML Email in Zoho Books

                                                                                                              Is it possible to create custom html email template in zoho books. 
                                                                                                            • Agents permission per department

                                                                                                              Hi Team, can I setup permission for each agent what they can do in each department, for example I want account department agents to only have view access to support department tickets and not allowed to assign or reply to clients. I am sure this would
                                                                                                            • Open a popup window from inside Record A and stay on the record after saving Record B

                                                                                                              Hello community, Perhaps you can help me with the following topic. I have a form A with a decision box. When this decision box is checked, a form B pops up. Once Form B is saved, I need to stay on Form A to continue entering data. I've observed the following
                                                                                                            • Don't allow scheduling service on same day

                                                                                                              Is there a way when setting up a Service for people to schedule to not allow them to schedule it for the same day, only a future date? We don't want people scheduling their meeting/service without giving us time to prepare for it.
                                                                                                            • How to get the call recording external ID via desk API

                                                                                                              I have enabled phonbridge integration with Zoom Call. I am trying to access the call recording in Zoom by calling Zoom API. I have built a Desk workflow to trigger on a new call, to call a custom function. when calling the API, the response doesn't contain
                                                                                                            • Presenting the brand new Zoho Bookings!

                                                                                                              Hello everyone, Greetings from Zoho Bookings! We're happy to announce a new version of our product with enhanced features to simplify scheduling, coupled with a sleek interface and improved privacy across teams. Here's what you can expect from the latest
                                                                                                            • Expense Entry Error When Trying To Save (Related To Taxes)

                                                                                                              Hey folks, I've been trying to enter my first few expense entries in Zoho Books and I'm faced with the following error. "You cannot perform tax related operations when you are not registered for tax." But I have my HST/GST enabled and the tax rates are
                                                                                                            • Need the ability to have read only fields on a form.

                                                                                                              There needs to be functionality in Creator that allows a field on a form to be read only. Most screen building software applications have this capability. I know you can hide certain fields from specific users and that you can also make the whole form read only but that's not the functionality I need. I want to be able to create a form where certain fields are editable and other are for display purposes only (read only). For example if the form was displaying information on an item that the user
                                                                                                            • Onboarding Zoho sign documents?

                                                                                                              I was wondering something about using the Zoho sign integration with the candidate onboarding process. We set up the entire onboarding process and we have added documents that the candidate needs to review and sign digitally using Zoho Sign. This part
                                                                                                            • Email Templates - Is There a Ticket Placeholder for Billing Entity ID

                                                                                                              Was looking to add Billing Entity ID as a placeholder in a ZoHo email template. https://help.zoho.com/portal/en/kb/desk/customization/templates/articles/creating-and-managing-email-templates#Guide_to_Placeholders e.g. the placeholder for Account would
                                                                                                            • Integration with Woocommerce

                                                                                                              Hi, Do you have plan to make integration with other e-commerce platforms, for example Woocommerce / Shopify / Magento ?  Thanks. 
                                                                                                            • Se puede mover un Cliente de un modulo a otro personalizado

                                                                                                              Hola, tengo una duda que me gustaría resolver: Actualmente trabajo con dos módulos: Seguimiento de Venta y Cierre de Ventas . Mi objetivo es que, cuando desde el módulo de Seguimiento se marca una venta como "Venta Efectiva" , el cliente sea movido al
                                                                                                            • Creating a whatsapp channel in instant messaging in zoho desk - error Oops, something went wrong. Please try again later.

                                                                                                              Creating a whatsapp channel in instant messaging in zoho desk - error Oops, something went wrong. Please try again later.
                                                                                                            • Export Data & Attachments

                                                                                                              Hi, I am wondering whether it is possible to create an export of all data in creator, including attachments, for either backup purposes, or migration purposes. Thanks.
                                                                                                            • Apply partial payments to invoices from the Banking Module

                                                                                                              We need this! Why is this not possible?
                                                                                                            • Zoho Desk: Q1 2025 | What's New

                                                                                                              Hello everyone, Our first release for the year 2025 is here! Check out the Release Notes for more details The diverse capability of AI and its avatars has been the center of attention lately, and we've made some significant strides in this area. We now
                                                                                                            • Feature Request Improve parent-child relationship visibility

                                                                                                              Hi team, The Parent-Child ticket feature is great, but I've struggled to see the relationship between tickets when using ticket list views. It would be a great quality of life enhancement for users if child tickets were nested under parent tickets in
                                                                                                            • What is Resolution Time in Business Hours

                                                                                                              HI, What is the formula used to find the total time spent by an agent on a particular ticket? How is Resolution Time in Business Hours calculated in Zohodesk? As we need to find out the time spent on the ticket's solution by an agent we seek your assistance
                                                                                                            • Issues with Dashboard Filter and KPI in Zoho Analytics (CAGR)

                                                                                                              Hi everyone, I'm trying to build a CAGR (Compound Annual Growth Rate) KPI in Zoho Analytics, but I'm running into some issues with filter synchronization. Here's the scenario: I created two test reports: One that filters results from 2021 to 2025. Another
                                                                                                            • need a third party to fix email authentication dns records

                                                                                                              at my wit's end - zoho began giving me spf, dmarc, dkim errors two weeks ago fussed with it since and now it seems dkim is the only problem and when i added the dkim record with the key from zoho mail it still wont work tired of this, need someone who
                                                                                                            • How do i move multiple tickets to a different department?

                                                                                                              Hello, i have several tickets that have been assigned to the wrong department.  I am talking about hundreds of automatically generated ones that come from a separate system. How can i select them all at once to move them to another department in one go? I can select them in "unsassigned open tickets view" but i can't find a "move to another department" option. I also can't seem to assign multiple tickets to the same agent in that same view. Could somebody advice?
                                                                                                            • Zoho Books Sandbox environment

                                                                                                              Hello. Is there a free sandbox environment for the developers using Zoho Books API? I am working on the Zoho Books add-on and currently not ready to buy a premium service - maybe later when my add-on will start to bring money. Right now I just need a
                                                                                                            • Add Button on Tickets

                                                                                                              is there a way I could add another button on the ticket aside of "closed ticket" only. Like I want to add another button "Send & Pending", "Pending for Response" like that.
                                                                                                            • Enhancements in Canvas

                                                                                                              Dear All, Greetings! Canvas lets you design the record details page to suit your brand or business preferences. We are glad to introduce the following enhancements to uplift your design experience. Reusable Components Style Presets Let's go! Reusable
                                                                                                            • Currency fields and decimal places in CRM email templates

                                                                                                              Hi, How do I get more than the standard 2 decimal places showing in a Currency field, on an email template? In the Layout for my Currency field, it is set to 6 decimal places. I want to show up to 6 places in the email template (unrounded). See attached
                                                                                                            • Include Secondary Contacts (CCs) on Workflow Alerts

                                                                                                              Hi There, We use the Supervise Rules and Workflow Alerts to send automated messages to contacts in Zoho Desk. Most often, we are sending the ticket contact (our client) a reminder that we are waiting on their reply to our most recent message. The problem
                                                                                                            • Zoho Desk blank page

                                                                                                              1. Click Access zoho desk on https://www.zoho.com/desk/ 2. It redirects to https://desk.zoho.com/agent?action=CreatePortal and the page is blank. Edge browser Version 131.0.2903.112 (Official build) (arm64) on MacOS
                                                                                                            • Adding a lead by sending email message

                                                                                                              Hello, Our Zoho Mail is integrated with Zoho CRM (we have Enterprise) and we can add new leads to CRM right from the web interface/panel of Zoho Mail using buttons at the bottom right corner of the screen. This is very handy. We add leads on a regular basis.    I was wondering though if it's possible to add a lead to CRM by simply forwarding an email message to a certain e-mail address. For example, in Evernote one can add a new note by sending an email message (with certain parameters) to a custom
                                                                                                            • Ask the Experts 19: Live Expert Panel Discussion - Inside Zoho Desk Spring Release 2025

                                                                                                              Hello again! Have you ever needed quick insights into key indicators to help manage and streamline specific operations? Have you started using AI to enhance your customer service in Zoho Desk? From configuring simple bots using Guided Conversations to
                                                                                                            • Ability to select Vendor Credits when creating Vendor Payments

                                                                                                              When making vendor payments there should be the option to select open vendor credits, this way the payment shows what bills and credits are being used for the payment Right now the vendor credits must be applied to the bills prior creating a payment,
                                                                                                            • No Sales Returns on SO's with Dropped Shipped items + Inventory Items

                                                                                                              We have encountered an issue in Zoho related to sales orders that include both dropshipped items and inventory items. Specifically, it is currently not possible to create sales returns for the company’s own inventory items from these sales orders. This
                                                                                                            • Show both Vendor and Customers in contact statement

                                                                                                              Dear Sir, some companies like us working with companies as Vendor and Customers too !!! it mean we send invoice and also receive bill from them , so we need our all amount in one place , but in contact statement , is separate it as Vendor and Customer, 
                                                                                                            • Filter a report for a specific bank and a specific transaction type (interest income)

                                                                                                              I am trying to run a report - any report - on a specific bank account for the interest income. I do not see it as an option. I can see the Bank Account under Account in the Filters, and I can see the Interest Income under Account in the Filters But I
                                                                                                            • ZMA v2 : Unable to delete a trigger from existing journey with several triggers

                                                                                                              I have multiple triggers on a single journey and need to delete one. However there isn't the function to do so, no delete icon or settings bar, no right click options of any kind. Every change I make affects all triggers ... How can I remove one of these
                                                                                                            • How to track the source of form submissions using referrer names in Zoho Forms?

                                                                                                              Ever wondered where your users are accessing your form links from? By tracking the origin of your form entries—whether it's from social media, email campaigns, direct links, or embedded on your website—you can identify which channels are driving the most
                                                                                                            • Snapchat

                                                                                                              Are there any plans to add Snapchat to Zoho Social or is there any API that we can use to integrate into Zoho.
                                                                                                            • Showing meeting acceptances in CRM that originated from Outlook

                                                                                                              Hello Zoho Team, We send meeting invitations from Zoho CRM. Many of our recipients use Outlook and therefore use the RSVP buttons from Outlook to respond. They rarely, if ever, use the RSVP buttons from the Zoho invitation. Unfortunately, the meeting
                                                                                                            • Widget JS SDK to Upload a photo to a record in a Module

                                                                                                              Good day,  I would really appreciate it if someone can assist me. I have written a widget, to be used in a Custom Module in CRM.  My goal: I want to upload a photo from my computer and display it in die "upload image" field. I am using the JS SDK: https://help.zwidgets.com/help/v1.1/index.html
                                                                                                            • Easy way to create task from call

                                                                                                              In Bigin I would like to have easy way of creating the tast directly from the call. Now after the call I need to enter company record and create task there. There must be some easier and more user friendly way to create new task after the call!
                                                                                                            • Zoho Creator Deluge - dynamically change fields depending on user input of field1 or field2

                                                                                                              Hi everyone and happy holidays! Hope that someone will help me figure out a solution to my problem… In my form there are currency, formulas and lookup fields. I’m well aware, that formulas fields if marked visible on form, cannot be hidden anywhere (like
                                                                                                            • Next Page