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




                                      Zoho Desk Resources

                                      • Desk Community Learning Series


                                      • Digest


                                      • Functions


                                      • Meetups


                                      • Kbase


                                      • Resources


                                      • Glossary


                                      • Desk Marketplace


                                      • MVP Corner


                                      • Word of the Day



                                          Zoho Marketing Automation


                                                  Manage your brands on social media



                                                        Zoho TeamInbox Resources

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

                                                                                                  • [Product update] Instagram Profile Integration with Zoho Analytics

                                                                                                    Dear Customers, We want to inform you about an update affecting the Instagram Profile integration with Zoho Analytics. Meta will deprecate certain metrics from January 8, 2025 as per their announcement in this document. To ensure uninterrupted syncs in
                                                                                                  • Nimble enhancements to WhatsApp for Business integration in Zoho CRM: Enjoy context and clarity in business messaging

                                                                                                    Dear Customers, We hope you're well! WhatsApp for business is a renowned business messaging platform that takes your business closer to your customers; it gives your business the power of personalized outreach. Using the WhatsApp for Business integration
                                                                                                  • When Email is sent, automatically have information be stored inside.

                                                                                                    Hi there, I just wanted to know if it was feasible to make it so that when i receive an email to a specific email, all of the information or contents would be filled up inside of leads. This will help me with another side of the process that im working
                                                                                                  • Zoho CRM - how to change SuperAdmin

                                                                                                    Hi there - I'm looking for current guidance on how to change the Zoho superadmin for our company - I'm transitioning out of my role and need to delegate to another adminisstrator
                                                                                                  • Translation support expanded for Modules, Subforms and Related Lists

                                                                                                    Hello Everyone!   The translation feature enables organizations to translate certain values in their CRM interface into different languages. Previously, the only values that could be translated were picklist values and field names. However, we have extended
                                                                                                  • Automatic Portal invite

                                                                                                    We have numerous customers we move through a blueprint in deals, when they get to a certain point we need to give them portal access, how can this be done through deluge or a workflow?
                                                                                                  • Pass json to ZDK.Client.openMailer TO parameter

                                                                                                    Hello I try to make send emails to a list of emails with : ZDK.Client.openMailer({ from: 'example@zoho.com', to: details_output, subject: 'test Mailing List', body: 'Test Mailing List Body' }); where details_output is an array like : [{ "email": "testcarte18078@test.com",
                                                                                                  • Create a field in Leads that is displayed in Contacts and Accounts

                                                                                                    I am trying to set it up so that if I create a field "Deals" which I have set up in the Deals module, that any selection made in the Leads module when this is converted to Contact that the selection made under the Deals field in the Leads module will
                                                                                                  • Zoho Analytics in 2024: A look back

                                                                                                    Happy new year to everyone in the Zoho Analytics community! As we welcome 2025, here's a look back of important happenings in 2024.
                                                                                                  • Approval Processes Issue

                                                                                                    Hello, I have a significant issue that could potentially cause serious problems for our company. We have developed a new module that we use as a payment request module. In short, payment requests are made through this module and are approved by different
                                                                                                  • Useful enhancements to Mail Merge in Zoho CRM

                                                                                                    Dear Customers, We hope you're well! We're here with a set of highly anticipated enhancements to the Mail Merge feature in Zoho CRM. Let's go! Mail Merge in Zoho CRM integrates with Zoho Writer to simplify the process of customizing and sharing documents
                                                                                                  • Bulk create tasks - Zoho Projects API

                                                                                                    Hi Zoho/Community, I am trying to create multiple tasks in a single API call, is there a way we can combine multiple request bodies into one single payload? The issue I am facing is the rate limiting on the API, I wanted to create certain amount of tasks
                                                                                                  • Function Needed: Update Account or Contact Profile Image

                                                                                                    Hey there! Zoho doesn't have the ability to automatically populate company logo or contact images once a domain/email is added to a record. This can be done via Clearbit's Logo API: https://clearbit.com/logo  I would like to create a deluge script that
                                                                                                  • Whatsapp Limitation Questions

                                                                                                    Good day, I would like to find out about the functionality or possibility of all the below points within the Zoho/WhatsApp integration. Will WhatsApp buttons ever be possible in the future? Will WhatsApp Re-directs to different users be possible based
                                                                                                  • Mass Email and security

                                                                                                    When I send a mass email to multiple candidates, can they see each other's emails?
                                                                                                  • Context and convenience just got better with Zia's email intelligence

                                                                                                    Dear Customers, We hope you're well! We are in 2024, and email as a tool is only getting more powerful each day. While it enables seamless daily correspondences, we are here with a set of abilities that will enhance your user experience and save several
                                                                                                  • Add home page or dashboard in CRM customer portal

                                                                                                    is it possible to add home page or dashboard in CRM customer portal?
                                                                                                  • Want to upload images to custom image fields using zoho crm api v2.

                                                                                                    Hi i want to upload image to my custom image field from third party application using zoho crm api v2 . Please tell me how i can do this? Thanks
                                                                                                  • Zoho mail stopped receiving emails

                                                                                                    My Zoho email addresses that are linked to a domain suddenly stopped receiving messages yesterday, even though I've been using Zoho mail without problems for 1,5 years. I receive this reply to test emails: "553 Relaying disallowed". Due to this, my SMTP
                                                                                                  • WebDAV / FTP / SFTP protocols for syncing

                                                                                                    I believe the Zoho for Desktop app is built using a proprietary protocol. For the growing number of people using services such as odrive to sync multiple accounts from various providers (Google, Dropbox, Box, OneDrive, etc.) it would be really helpful if you implemented standard protocols such as WebDAV / FTP / SFTP so that alternative inc clients can be used.
                                                                                                  • Download all the Attachment From Document Section Zoho Project

                                                                                                    Hello Team, I hope this message finds you well. I am currently facing an issue while trying to download all the documents associated with a Zoho project. Here’s the scenario: We have more than 150 tasks in a single project. Each task may have documents
                                                                                                  • Is there a way to automatically move a task from a different tasklist to another tasklist when certain criterias are met?

                                                                                                    Hi there, Im new to zoho projects and i was wondering if there was a way to automatically move a task from a tasklist to another tasklist based on criteria such as when the task status is updated to completed and have it move to the tasklist that is named
                                                                                                  • Checklist/ save to onedrive/ a group of items invoicing in Zoho FSM

                                                                                                    hi, is there a way to add a specific checklist to any WO without passing eachtime by the model customization? can we save file such picture directly in our sharepoint ak onedrive? is there any way to add a group of item pre defined to make invoicing easier
                                                                                                  • Creating smart filters manually

                                                                                                    Hi Team, One of my colleagues accidentally deleted the Notification folder in Zoho Mail. Now all the emails are directing to spam instead of inbox. Is there any way to create the smart filter manually?. With Regards, Logeswar V
                                                                                                  • Change Last Name to not required in Leads

                                                                                                    I would like to upload 500 target companies as leads but I don't yet have contact people for them. Can you enable the option for me to turn this requirement off to need a Second Name? Moderation update (10-Jun-23): As we explore potential solutions for
                                                                                                  • Auto-sync field of lookup value

                                                                                                    This feature has been requested many times in the discussion Field of Lookup Announcement and this post aims to track it separately. At the moment the value of a 'field of lookup' is a snapshot but once the parent lookup field is updated the values diverge.
                                                                                                  • Zoho Finance Limitations 2.0 #12: Can't sync Books System Fields (Item Category or Preferred Vendor) to CRM Products. Double entry required

                                                                                                    We add products to Books and sync them to CRM whenever updates are done. However I still have to do double entry because the Books "Item Category" and "Preferred Vendor" fields are not available as options to sync. Scenario Workflow I add a new product
                                                                                                  • Copy across spreadsheets in Zoho Sheet

                                                                                                    Now, you can copy your sheets to other spreadsheets or create a new spreadsheet with them. Not just sheets, copy a cell/range and paste it on any spreadsheet with formats and formulas unchanged. Copy cells/ranges Copy cells/ranges to same/different spreadsheets using Copy & Paste options, or Ctrl+C and Ctrl+V shortcuts. Copy sheet To the same spreadsheet The feature for creating a copy of a sheet in the same spreadsheet is now available as 'Duplicate'. Into a new spreadsheet Want to start a new spreadsheet
                                                                                                  • Rich-text fields in Zoho CRM

                                                                                                    Hello everyone, We're thrilled to announce an important enhancement that will significantly enhance the readability and formatting capabilities of your information: rich text options for multi-line fields. With this update, you can now enjoy a more versatile
                                                                                                  • 100 record view limitation

                                                                                                    I have just migrated from another CRM and am starting in ZOHOcrm with over 5000 contacts. It seems that my searches and sorts are limited to 100 live records....or am I missing something. This seems to be very limiting...in a lot of scenarios (mass email,
                                                                                                  • Used & Non used Inventories

                                                                                                    I have a list of used inventories with campaign names and creation dates. I want to show the count of used and non-used inventories in a dashboard with a date filter (like last 30 days, last 3 months). I’ve written a query for the count, but the date
                                                                                                  • How to search Locked Record?

                                                                                                    Hi, I have script like below, however seems this cannot search those locked record. what para I can add to search locked record? var invoice_info_list = ZDK.Apps.CRM.Invoices.searchByCriteria("(Sales_Order:equals:"+ so_record_id +")");
                                                                                                  • My Zoho Story #8 ネットワイズ フチーロさん:プロジェクト管理から顧客対応までをZoho One で実現

                                                                                                    こんにちは。Zoho コミュニティチームです。 「My Zoho Story」では、Zoho の活用により自社ビジネスを成長させてきた軌跡を、さまざまな業界のユーザーにお聞きします。その経験や知見を、Zoho 活用の幅を広げる参考にしていただきたいと考えています。 今回ご登場いただくジェフリー フチーロさんは、ウェブサイト制作・デザイン、ウェブマーケティングを得意とするデジタルマーケティング会社、株式会社ネットワイズ(netwise)でオペレーションディレクターおよびZoho 運用責任者として活動されています。フチーロさんと同社がどのようにZoho
                                                                                                  • Kiosk Studio wrap-up | How our community used kiosks in 2024

                                                                                                    Hello, everyone! Happy new year! The end of 2024 has been busy, and 2025 promises to be bigger and better. As we ring in the new year, let's rewind and look at Kiosk Studio, our no-code customization tool. The past 300 days have seen the CRM community
                                                                                                  • Limit excceding issue in zoho creator

                                                                                                    I am transferring data from Zoho Books to Zoho Creator using a Deluge script. However, I am frequently encountering a "limit exceeding error," which seems to be related to the Deluge statements limit. I reached out to Zoho Support, and they informed me
                                                                                                  • Getter error message Number of statement execution limit exceed Line:(216)

                                                                                                    Hi, this script is giving me error message "Number of statement execution limit exceed Line:(216)". Please advise htmlpage Pay_Period_Details(PayPeriodID,AgentID,ShowPrint,start_range,end_range) displayname = "Pay Period Details" content <%{ /* Get The current Pay Period Record */ Int_Pay_Period_ID = PayPeriodID.toLong(); Current_Pay_Period_Record = Pay_Period[ID == Int_Pay_Period_ID]; Previous_Pay_Period_ID = thisapp.Application.GetPreviousPayPeriodID(Current_Pay_Period_Record.ID); /* Checking Agent
                                                                                                  • How create deal with label added using api

                                                                                                    Hi, I am creating automations in n8n for Zoho CRM. I want to create a new deal with a label added at the same time. However, I keep getting an error. Using the API, I can create a deal successfully, but when I try to add a label during the deal creation,
                                                                                                  • Message as a bot to user now says: "The message recipient id sent in the API is your own user id. You cannot send messages to yourself."

                                                                                                    Hi   I used to be able to have a bot message myself in cliq when something happened . Now the connector Message as a bot to user gives me this error when testing: Zoho Cliq says "The message recipient id sent in the API is your own user id. You cannot
                                                                                                  • Can I Integrate ADP Payroll with Zoho Books?

                                                                                                    Hi, I am hoping that I can integrate ADP Payroll with Zoho Books so that I do not need to manually input the payroll journal entries. Is this possible? If so, how do I do that?
                                                                                                  • Lookup field - Can I avoid using advanced search?

                                                                                                    I have a lookup field in my app that has surpassed 500,000 records, now basic search is disabled and I'm forced to use advanced search. That adds multiple steps to what used to be very simple. Before: Select field > Type last digits of product code and
                                                                                                  • Next Page