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 FSM Video Tutorials


              All-in-one knowledge management and training platform for your employees and customers.






                                    Zoho Developer Community




                                                          • Desk Community Learning Series


                                                          • Digest


                                                          • Functions


                                                          • Meetups


                                                          • Kbase


                                                          • Resources


                                                          • Glossary


                                                          • Desk Marketplace


                                                          • MVP Corner


                                                          • Word of the Day


                                                          • Ask the Experts



                                                                    • Sticky Posts

                                                                    • Announcing the new SKILL.md for Zoho CRM and the updated OAS repository!

                                                                      We are introducing a new zoho-crm skill to make working with Zoho CRM Developer tools (like APIs, functions, widgets, client scripts, queries etc) easier and faster, with the help of AI in your preferred AI harness like Claude Code, Codex, Cursor, VSCode
                                                                    • Kaizen #261 : Using Zoho CRM Skill to generate complex COQL queries

                                                                      Hello everyone, In the previous Kaizen posts, we introduced the zoho-crm SKILL.md and discussed how it can help you when you are working with Zoho CRM APIs and Client Script. In this Kaizen, we will focus on using the Zoho CRM `SKILL.md` with GitHub Copilot
                                                                    • Kaizen #256 - Build an Arrival Readiness Web Tab in Zoho CRM

                                                                      Hi everyone! Welcome back to the Kaizen series! In the post, we discuss a use case in hospitality industry: how an Arrival Readiness web tab widget can be used to let reception staff identify and resolve issues before arrival of guests. Use case In the
                                                                    • Kaizen #198: Using Client Script for Custom Validation in Blueprint

                                                                      Nearing 200th Kaizen Post – 1 More to the Big Two-Oh-Oh! Do you have any questions, suggestions, or topics you would like us to cover in future posts? Your insights and suggestions help us shape future content and make this series better for everyone.
                                                                    • Kaizen #226: Using ZRC in Client Script

                                                                      Hello everyone! Welcome to another week of Kaizen. In today's post, lets see what is ZRC (Zoho Request Client) and how we can use ZRC methods in Client Script to get inputs from a Salesperson and update the Lead status with a single button click. In this


                                                                    Manage your brands on social media



                                                                          Zoho TeamInbox Resources



                                                                              Zoho CRM Plus Resources

                                                                                Zoho Books Resources


                                                                                  Zoho Billing 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

                                                                                                      Get Started. Write Away!

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

                                                                                                        Zoho CRM コンテンツ


                                                                                                          Nederlandse Hulpbronnen


                                                                                                              ご検討中の方





                                                                                                                        • Recent Topics

                                                                                                                        • Supervisor Rules --> Custom Function

                                                                                                                          Hello, currently I can't add a custom function to a supervise rule. Is there a reason for this? Background: We have BluePrint managed tickets and actually we have a Supervise rule which should set the ticket to "closed" after 168 hours since the last
                                                                                                                        • Erro

                                                                                                                          Subject: CRM Standalone Function creation returns INTERNAL_ERROR Hello Zoho Support, I am trying to create a Standalone Deluge Function in Zoho CRM for a lead intake REST API. The CRM account reports that the Standalone category is enabled, but function
                                                                                                                        • Digest Septembre - Un résumé de ce qui s'est passé le mois dernier sur Community

                                                                                                                          Bonjour chère communauté ! 👋 Le mois dernier a été riche en nouveautés, en échanges et en découvertes ! Retrouvez ici les contenus les plus utiles, les discussions les plus intéressantes et plus encore. En septembre, nous avons mis en lumière trois nouveautés
                                                                                                                        • New Update: Convert External Users in Bulk in Zoho Directory

                                                                                                                          Greetings to all Zoho Directory users out there! We’re excited to introduce a new update that makes user management in Zoho Directory even more efficient; you can now convert external users in bulk! Earlier, admins could convert only one external user
                                                                                                                        • Presenting ABM for Zoho CRM: Expand and retain your customers with precision

                                                                                                                          Picture this scenario: You're a growing SaaS company ready to launch a powerful business suite, and are looking to gain traction and momentum. But as a business with a tight budget, you know acquiring new customers is slow, expensive, and often delivers
                                                                                                                        • API - Bank Accounts | Reconciliation Discrepancy

                                                                                                                          Unless I'm reading it wrong, the documentation for the Bank Reconciliations API is inconsistent with itself. https://www.zoho.com/books/api/v3/bank-accounts/#create-a-bank-reconciliation The text definition says that the transaction_id should be a string,
                                                                                                                        • Employment Contract / HRMS Documents - Zoho People

                                                                                                                          How do I create customized HR documents for disbursal from Zoho People ? Example, say offer letters ? appointment letters ? Memos ? We want to be able to preset these in one or ther other form and issue them to employees who are in Zoho People.
                                                                                                                        • Mobile authentication for Zoho Creator portals

                                                                                                                          Note: This feature was previously available in beta for IN data center users on request. It is now generally available for all users in the IN and US data centers on paid plans of Zoho Creator. Currently, it will be available only for Indian (+91) mobile
                                                                                                                        • HOw to disable or block OTP login on browser.

                                                                                                                          Hi Support, One of my employee tried & successfully logged in via OTP login mode on his mobile device even though user does'nt have login password . As per our company policy we don't allow user to login on any other device. This feature is available
                                                                                                                        • Change email address

                                                                                                                          I would like to change the email address to info@gogetherenterprises.com
                                                                                                                        • Enhanced audit trail in Zoho Creator

                                                                                                                          Hello everyone, We're pleased to announce that the Audit Trail feature has been significantly enhanced by expanding its scope to give you a more complete picture of activity across your applications. What was once a simple record-and-report log is now
                                                                                                                        • Allocating inventory to specific SO's

                                                                                                                          Is there a way that allocate inventory to a specific sales order? For example, let's say we have 90 items in stock. Customer 1 orders 100 items. This allocates all 90 items to their order, and they have a back order for the remaining 10 items which could
                                                                                                                        • Introducing native agents: Configure your CRM with natural language

                                                                                                                          Hello all, Configuring your CRM just got a lot faster. We're introducing native agents into Zoho CRM that configure your settings using natural language. Instead of navigating multiple screens, describe what you need and the agent builds it for you. What's
                                                                                                                        • Transferring CRM Templates

                                                                                                                          I have two different scenarios for transferring the CRM template and would like to know if it is possible to do for either.   1.  When designing my CRM template, I created all the fields in the Leads module.  I have not duplicated all of the fields (or their positions on the page) in other modules like the Contacts, Potentials, Accounts, etc.  Once I get my Leads template designed the way I want, I would like to copy the fields and their page positions to the other modules.  Is it possible to do
                                                                                                                        • Is it possible to clone my Lead module layout to Customer and Potential layouts?

                                                                                                                          I've customized all fields and their order for Leads module and I would like to know if I'm able to clone those fields into another modules, only to avoid repeated work. Awaiting.
                                                                                                                        • URGENT: Stalled DC Migration >72 Hours - Records Locked [Ticket #: 167813877

                                                                                                                          The DC migration was started on 1st October at 6 pm and we were informed migration period as 48 hours but even after more than 72 hours, the migration seems still in progress. We sent two emails to check the status but no responses. We need the migration
                                                                                                                        • Error AS101 when adding new email alias

                                                                                                                          Hi, I am trying to add apple@(mydomain).com The error AS101 is shown while I try to add the alias.
                                                                                                                        • Account not Active For any support or queries, kindly contact support@zohomail.com

                                                                                                                          HI! I am trying to sign up to Zoho Mail which is not working. All I can see is the following error message, " Please help me. Account not Active For any support or queries, kindly contact support@zohomail.com"
                                                                                                                        • Introducing Zoho Commerce 2.0 — It's more than just selling!

                                                                                                                          Hello! We are proud to launch Zoho Commerce 2.0, a reimagination of how online businesses look, feel, and function. This launch is both timely and symbolic, as we reaffirm our commitment to empowering small and medium enterprises with powerful, yet simple-to-use
                                                                                                                        • Zoho Thrive connection to off-line purchases

                                                                                                                          Is it possible for Zoho thrive to connect to subscriptions or Books and pull purchase data from clients who purchase off-line or maybe through a different sales department where items are not listed on a website for sale? Say I have a customer that signed
                                                                                                                        • Payroll Options

                                                                                                                          Would like to see a payroll service implemented; Maybe not a true payroll but at least the ability of tracking payments to employees without making them a vendor. please help. Thanks. I didn't find the right solution from the internet. References: https://zohofinance.uservoice.com/forums/283818-zoho-books
                                                                                                                        • Esta dirección de correo electrónico ya se encuentra en uso en otra organización... agregar usuarios

                                                                                                                          Buenos dias , tengo este problema a la hora de agregar usuarios mi dominio es implementos.com.pe
                                                                                                                        • How to setup noreply@ example.com

                                                                                                                          How do I setup noreply@example.com so the mail never gets delivered. I currently have a catchall setup aswell.
                                                                                                                        • How do you associate multiple contacts to a deal in the mobile app?

                                                                                                                          When opening a deal in the mobile app, only one customer shows as the contact. How can we add multiple contacts on our mobile device?
                                                                                                                        • Zoho Books Support

                                                                                                                          Dear Team, Zoho Books offers a demo before you purchase zoho books. But after that when he actually purchases the product he has to rely on toll free number or help documents. But this might get frustrated in the initial period. Specially in initial period.
                                                                                                                        • Linking Multi-UOM Barcodes to Products in Zoho Books

                                                                                                                          Greetings, I'm using Zoho Books for retail shop and I'm running into a bit of a challenge with products that have multiple Units of Measurement (UOMs) and corresponding barcodes. For example, I sell cigarettes both as individual packets and in cartons
                                                                                                                        • Has anybody managed to do ANYTHING with Zoho CRM Zia Agents?

                                                                                                                          I have 'hired' a few agents from the 'store', and also built the super simplest Agent I could think of (retrieve the email address for a given Contact), and none of them work. I get errors like "LLM Inference failed" even from the store Agents (e.g. "Search
                                                                                                                        • custom function

                                                                                                                          I want to send a request following the webhook pattern with Endpoint Type Intranet, I received a Zoho access response from Daniel. Please advise on how to implement invokeUrl with Endpoint Type Intranet and a probe
                                                                                                                        • ERROR CODE :554 - Your access to this mail system has been rejected due to poor reputation of a domain used in message transfer

                                                                                                                          This message was created automatically by mail delivery software. A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. *****, ERROR CODE :554 - Your access to this mail system has been rejected due
                                                                                                                        • Function #46: Auto generate list of lapsed customers using Custom Button

                                                                                                                          Hello everyone, and welcome back to our series! Customer retention is one of the key factors that impact the long-term success and sustainability of a business. High customer retention rates indicate satisfied customers, quality products or services,
                                                                                                                        • Lookups and Custom Modules

                                                                                                                          I created a Custom Module that I'm calling "Item Purchasing Group". This module will store information for groups of Items that must be purchased together (including minimum overall quantities and/or values, etc.). This will have a one-to-many relationship
                                                                                                                        • Zoho Writer for Android - Headings

                                                                                                                          Hello Zoho team, I have created structured doc with headings in writer web version on pc. Then I have opened it in my phone. Write is crashing while used function: menu "three dots", Document Navigation, Headings. Zoho Writer for Android 6.1.4 Samsung
                                                                                                                        • Can't connect to POP and SMTP over VPN

                                                                                                                          I use Thunderbird to access Zoho Mail via POP and SMTP. I have configured an app-specific password for Thunderbird to use. Everything is properly configured and works correctly — until I enable my VPN. I'm using a paid commercial VPN service (Mullvad).
                                                                                                                        • Possible to reorder Pipelines position?

                                                                                                                          I have multiple Pipelines and want to reorder their positions, so that in the Deals module record for the Pipeline field, I have them ordered in a certain way. Is there a way to reorder the position of the Pipelines without deleting existing Pipelines
                                                                                                                        • Pleas unblock E-Mail-Adress service@montana-energie.de / kontakt@montana-energie.de

                                                                                                                          Dear Zoho Support, Could you please unblock service@montana-energie.de / kontakt@montana-energie.de which belongs to a regular customer with whom we are having frequent business-related conversations. Thank you very much in advance, Erdem Kar homewise
                                                                                                                        • Unable to preview attachments using Apple Safari on Mac

                                                                                                                          When attempting to preview an image attachment in Zoho desk the image will fail to load and present a "missing" icon in the middle of the display.  This is using Safari 14.0.3 on macOS Big Sur 11.2.3.
                                                                                                                        • Kaizen #262 - Using Zoho CRM Skill to build Queries

                                                                                                                          Hello everyone! Welcome back to another edition of the Kaizen series, where we uncover powerful ways to extend and customize Zoho CRM. In the previous Kaizens, we explored how the zoho-crm skill can help developers work with Zoho CRM APIs, Client Scripts
                                                                                                                        • 【10/30福岡】他社はZoho CRM×AIをどう使う? 営業に役立つ実践デモ&事例解説|10〜12月のイベント予定も!

                                                                                                                          ユーザーの皆様、こんにちは! ゾーホージャパンの中野です。 10月30日(金)の福岡ユーザー交流会では、CRM×AIのデモ / 事例紹介と、 Zoho社員によるAIエージェントの解説を通じて、自社での活用を考えるヒントをお届けします。 ■ 福岡で学べる・話せる3つのこと ① CRM×AIで、営業の仕事はどう変わる? 株式会社etikaの宮村佳祐さんが、具体的な連携デモをご紹介します。 ・提案中の商談に、参考になる過去の類似受注案件を表示 ・打ち合わせの文字起こしをCRMに自動連携し、項目を更新 ・取引先のニュースを集約し、営業担当者へお知らせ
                                                                                                                        • #10 India Specifics: GST, GSTIN And E-way Bills

                                                                                                                          Meera's new client sent a purchase order, a vendor form, and one line that changed the whole invoice: "Invoices without a valid GSTIN and correct place of supply will be returned unpaid." She had entered her own GST details. The customer's details were
                                                                                                                        • Invoke a Widget buttons not opening in Bigin web – open_in missing from response

                                                                                                                          Hi, I’m seeing an issue with Invoke a Widget custom buttons in Bigin web. In the Bigin Developer Sandbox, the button works correctly and the custom button response includes: "open_in": "new_tab" However, once the topping is installed in a normal Bigin
                                                                                                                        • Next Page