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.






    • Recent Topics

    • Formatting Mailing Labels

      I want to use the "Print Mailing Labels" function on the drop down list, but I am not seeing a way to change the formatting on the mailing labels. At the moment, the information that appears on the mailing labels ARE NOT mailing addresses, but random information.  I would also like to change be able to change the size of the labels.  At the very least I would like to know what type of labels I can get that would be the correct size.  
    • CRM to Writer Mail Merge Preview not working

      When performing a mail merge from CRM to writer the preview function does not work. I get the following error. I am a Zoho one user on a ChromeOS. I have been successfully using mail merge from CRM to Writer about 4 years. This error seemed to coincide
    • Best practice : when to convert lead to Deal

      Hello, I'm new to Zoho and run my own business. To make sure I'm using Zoho correctly, when do I press convert, from Lead to Deal, at what stage in the conversion funnel/conversation. I want to make sure I can a) monitor status of all pending lead or
    • Show Call History During a Blueprint Transition in Leads Module

      Hi all, I have a Blueprint set up in the Leads module with a transition to Reattempt Call, which updates the lead status to Attempted Contact. I’d like to know if there’s a way to show the call history or at least a summary of how many call attempts have
    • How do I filter contacts by account parameters?

      Need to filter a contact view according to account parameter, eg account type. Without this filter users are overwhelmed with irrelevant contacts. Workaround is to create a custom 'Contact Type' field but this unbearable duplicity as the information already
    • How to delete more than 100 leads at a time.

      We are a call center and we need to upload fresh leads daily.  Is there any way to delete all leads only at once.  Currently we are deleting 100 at a time. Please anyone who can help. Thank you.
    • The Next Chapter for CRM for Everyone: Moving from Early Access to Phased Rollout for Customers

      #CRM25Q1 Hello Everyone, Until now, CRM for Everyone has been available in early access mode exclusively for users who opted to try the new version. We are now transitioning to a phased release, starting with the basic edition. We are thrilled to announce
    • Canvas for related lists

      Hey, we would like to customize our related lists. For us, it would make more sense to present the data from an assigned record vertical instead of horizontal. Can we get a related list Canvas view?
    • Standalone custom function not generating logs

      Why dont't standalone custom functions generate logs when the're called from another function? I have some functions (workflow, buttons and blueprint) that have common parts, so I put that part in a standalone function which is called from the others.
    • Show Zoho Books Retainer Invoice in Zoho CRM

      Hi Support, How can I get Retainer Invoices created in Zoho Books to show in Zoho CRM? If a sales person needs to collect an upfront deposit, they should be able to see that the retainer invoice has been created and paid. Thanks, Ashley
    • Feature Request - Zoho Books - Add Retainer Invoices to CRM/Books integration

      Hi Books Team, My feature request is to include Retainer Invoices in the finance suite integration with Zoho CRM. This way we will be able to see if retainer invoices have been issued and paid. I have also noticed that when the generate retainer invoice
    • ACR Phone mobile app for logging phone calls into Zoho CRM

      ACR Phone is an Android app recording voice calls with additional features such as blacklist, cloud upload, call log and more. Use the ACR Phone extension for Zoho CRM to generate Leads and Contacts with the voice recording attached right after your phone
    • New in Zoho Sign: Allow recipients to review and change associated recipients

      Greetings! We are happy to announce the addition of a new recipient role, Manages recipients, in our signature workflows. This role enables a recipient to review, modify, or add details for any recipients associated with them in the workflow. This ensures
    • How can I throw an error / terminate the flow from within a custom function?

      As the subject says. I would like to be able to terminate a flow from within a custom function if certain conditions are not met. I know I could hook a decision box to the output of my custom function and check return variable, but hoping there is a more
    • Multiple Zoho Attendees in a Customer meeting

      We are having constraints with having to log duplicate meetings when we have 2 Zoho users attending a customer meeting. What are the options to resolve this? You can add participants, but you cannot report on them. What can be done to avoid creating so
    • iOS 18 is here! Discover the enhanced Bigin app with iOS 18, iPadOS 18 and macOS Sequoia.

      Hello, everyone! We are excited to be back with new features and enhancements for the Bigin app. Let us take a look at the new iOS 18 and iPadOS 18 features. The following is the list of features covered in this update: Control widgets. New app icons.
    • Multi-Select lookup field has reached its maximum??

      Hi there, I want to create a multi-select lookup field in a module but I can't select the model I want the relationship to be with from the list. From the help page on this I see that you can only create a max of 2 relationships per module? Is that true?
    • Password change restriction

      Can the administrator restrict users from changing their email password?
    • NOW Zoho Creator still cannot bulk download Image or File Upload Field

      The filedownloader has been deprecated for 5 years. Until now, we still cannot have a replacement tool. How can we bulk download the file that we uploaded to Zoho Creator. Previously, it was so simple to bulk download all those files. But now failed to
    • CRM API Search Record for Last Name equals "."

      When using the CRM API to look for all contacts with a lastname = "." The API returns an Invalid Query Reponse I have tried (Last_Name:equals:.) (Last_Name:equals:%5C.) (Last_Name:equals:\.) We have a scenario where the Last Name may not be known for
    • MS PowerApps Custom Connector

      Has anyone successfully connected to the API from MS PowerApps? The OAuth2 seems impossible to use from a platform like this.
    • Zdk-cli

      As i have tried to login to zdk cli as it returns this error ✔ Success! Logged in as JAYANTHAN ✖ Error during initialization of zdk api supported only in sandbox environment
    • 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
    • Its 2022, can our customers log into CRM on their mobiles? Zoho Response: Maybe Later

      I am a long time Zoho CRM user. I have just started using the client portal feature. On the plus side I have found it very fast and very easy (for someone used to the CRM config) to set up a subset of module views that make a potentially extremely useful
    • If Problema Formula

      Ceil(Datecomp(${Seguimiento de Venta.Fecha de la proxima visita},Now())/1440) Tengo porblema al plantear el If Quiero que si el valor es dega
    • Trying to do commission tracking with zoho crm, can i do a Lookup against multiple fields in a module?

      So i'm still designing my zoho one crm as i come over from salesforce. One of the things i'm trying to build is a commission tracking module. At some point i'll probably hire someone to help with custom code, I'm just proof of concepting it. I"m not sure
    • Mapping a new Ticket in Zoho Desk to an Account or Deal in Zoho CRM manually

      Is there any way for me to map an existing ticket in Zoho desk to an account or Deal within Zoho CRM? Sometimes people use different email to put in a ticket than the one that we have in the CRM, but it's still the same person. We would like to be able
    • Commerce service

      If I am selling a service in Commerce, how do I turn off shipping?
    • Customer Portal Zoho Desk | Sort ticket list

      Hello, If you view the ticket list inside the desk portal (https://xyc.zohodesk.eu/portal/de/myarea?departmentId=xyz) all tickets are displayed depending on the filters: department "my tickets" / "team tickets" status group/type channel My questions:
    • Customer/item(s) bought view

      Hello In Inventory/Customers/Transactions tab, how do I see what it is the customer actually ordered/bought without having to open each SO? Our customers buy a number of items thoughout the year. I've look at each transactions drop down, and no-where
    • ERROR: Product type cannot be changed for Items having transactions.

      I have mistakenly added a product type as goods for an item that was a digital service. Now when HSN/SAC became mandatory, this brought my attention to this error I did. So I tried changing the product type but it displayed this error message Product
    • Inventory Asset vs Finish Goods vs Work in Progress please explain or help me choose

      New to this so please if you can help in any way I would really appreciate it. So here we go. I make and sell and item which is made out of bunch of other items. (Composite Item). Now one of the parts that the item is made from is also a composite item.
    • WorkFlow to Update Custom Field in Sales Order with Tracking Information from Shipment of that Sales Order

      Hello All- I'd like to update the sales orders with the tracking information I enter in the shipping document. What is the proper variable to get the tracking information out of the shipping document? See attached.
    • ZOHO Desk-Enable Ticket Notification sound

      Hi, I answer the helpdesk tickets for Sevenstar. How can I enable the Ticket Notification sound when I receive a new ticket?
    • Differentiating between invoice templates when adding custom fields

      We are adding HS codes to the items which we would like published on our international customers invoices plus other export data required. We don't need this data on our domestic customer invoices. We have setup an invoice template for them but it if
    • Batch Tracking Enhancements In Zoho Inventory

      Hello users, We’re excited to announce that we’ve taken batch tracking to a whole new level in Zoho Inventory! We’ve made it more accessible and easier to use than ever. Here’s a quick look at the improvements: 1) A New Way To Create or Modify Batches
    • Workflow not triggered by custom function field update

      I have a simple workflow that triggers when a field is updated on a Deal page. It works fine when I "manually" update the field via "edit" on that Deal page. It does NOT however work or trigger when that same field is updated with a custom function. I
    • Version history for Zoho CRM Functions

      Hi Zoho Support, I am wondering, there is no topics been posted for requesting the Zoho CRM Custom Functions Version history. It would be great to have mandatorily needed feature in Zoho CRM custom functions. Is there any work going on for this feature.
    • Bookmark order

      Hi all, We have a very big document/template that requires manual editing after doing a mail merge. To make this easier, I thought I would add bookmarks to navigate to the areas that will require editing. I thought these would be in order that they appear
    • How do I associate an expense to multiple projects?

      How do I associate itemized expenses to multiple projects, like assigning each line to the respective project
    • Next Page