Kaizen 202 - Answering Your Questions | Testing and Using REST APIs in Widgets

Kaizen 202 - Answering Your Questions | Testing and Using REST APIs in Widgets



Hello Developers!

Welcome back to a fresh week of Kaizen! 

Thank you for your active participation in sharing feedback and queries for the 200th milestone. This week, we will look at the following queries related to widget:
  • Widget Testing 
  • Using REST API in Canvas Widgets: Make HTTP calls in widgets (e.g., to external tax or product APIs)
Here are the queries that we have already answered for you from this milestone:
  1. Kaizen #200 - Answering Your Questions | Token generation using the Python SDK
  2. Kaizen #201 - Answering Your Questions | Webhooks, Functions, and Schedules

Widget Testing

One of the queries we received was simply stated
Quote
Widget Testing
 without any specific context. Since the user has not provided detailed input, we are assuming this is about how to test a widget during development.

You can test your Zoho CRM widget locally using the Zoho CLI. Run the following command from the root directory of your widget project:

zet run

This launches the widget on a local server where you can validate the UI and functionality before pushing it live.


Since the localhost connection opens in a new tab and is not private, you will need to manually authorize it. 

Click Advanced, then choose Proceed to 127.0.0.1 (unsafe) to continue. 

Notes
Note

If your widget needs to access data from your Zoho CRM organization, such as fetching or updating records, it must be deployed within a Zoho CRM iframe. To do this, you should upload the widget through the Zoho CRM Widgets setup page.

We recommend using the sandbox environment in such cases before deploying the widget to your production environment.

Making HTTP Calls from Widget

Following is a query we received from a user:
Quote
Using REST API in Canvas Widgets: Make HTTP calls in widgets (e.g., to external tax or product APIs)
Yes. You can make HTTP requests to external services from any type of Zoho CRM widget using the ZOHO.CRM.HTTP object from the Widget JS SDK.

Canvas Widget - What's Supported? 

Though full widget support within Canvas is on our roadmap, currently, you can invoke widgets from a Canvas view using Client Script. This lets you render widgets inside fly-outs or pop-ups. Here is a quick start guide on how you can achieve it:

Create a Widget

1. Create a widget project and code your logic using Zoho CLI as explained in our widget help page.

2. In Zoho CRM Developer Hub, create a new widget and set the type as Button.



Create a Client Script

3. Navigate to Client Scripts in Developer Hub and click New Script.

4. You can create your script either in the Modules or Commands category based on your use case. 

For assistance, refer to the step-by-step guide on Creating Client Script and Commands.



In the Category Details section, ensure to select Canvas as the page type. Canvas views are supported in the following page contexts: List, Detail, Create, and Clone. 

Choose the one that aligns with where your widget needs to appear.


5. Here is the sample script to render widget in a pop-up

ZDK.Client.openPopup({
api_name: 'Canvas_Widget',
type: 'widget',
animation_type: 4, 
height: '450px',
width: '450px',
},
{
data: 'sample data to be passed to "PageLoad" event of widget'
}); 

Here is the sample script to render widget in a fly-out

ZDK.Client.createFlyout('myFlyout', { 
animation_type: 4, 
height: '600px', 
width: '500px'
}
);
ZDK.Client.getFlyout('myFlyout').open({ api_name: 'Canvas_Widget', type: 'widget' });

For detailed guidance, check out our Client API documentation on Pop-up and Fly-out.

You can also check out the Kaizen #99 on Rendering Widgets using Client Script for a detailed guide based on a real-time use case. 

Using REST APIs from External Applications

The ZOHO.CRM.HTTP object enables you to make secure API calls directly from the Zoho CRM widget. It acts as a proxy, routing requests through Zoho servers, which eliminates the need for external applications to support CORS.

While this SDK is primarily used for integrating third-party services, it also supports Zoho CRM API calls. This provides you with greater flexibility to:
  • Customize header and parameter structures
  • Maintain a consistent calling pattern for both internal and external APIs within the widget.
Here is a basic syntax of the SDK:

ZOHO.CRM.HTTP.<method>({
  url: "<request-url>",
  headers: {
       // Request headers as Key-value pairs
    "Authorization": "Bearer <token>" // example
  },
  params: {
    // Request params as Key-value pairs

   "ids": "1234567890" // example
  },
  body: "<stringified JSON>", // Required for POST, PUT and PATCH
})
.then(function(response) {
  console.log("Response:", response);
});

Supported Methods
  • ZOHO.CRM.HTTP.get({ ... })
  • ZOHO.CRM.HTTP.post({ ... })
  • ZOHO.CRM.HTTP.put({ ... })
  • ZOHO.CRM.HTTP.patch({ ... })
  • ZOHO.CRM.HTTP.delete({ ... })
For more detail check out the HTTP method section of JS SDK help page.

Samples using Zoho CRM Contact Roles API

Let us explore a complete CRUD (Create, Read, Update, Delete) example using Zoho CRM’s Contact Roles API.

These structures have to be used within the JS function where you are executing your code logic. 

POST Contact Roles


// Prepare the API request
        var request = {
          url: "https://www.zohoapis.com/crm/v8/Contacts/roles",
          headers: {
            Authorization: "Zoho-oauthtoken 1000.XXXXXXXXXXXXXXXXXXX265bcf20e4"
          },
          body: {
            "contact_roles": [
              {
                "name": "Sales Lead",
                "sequence_number": 1
              }
            ]
          }
        };
         // Make API call 
        ZOHO.CRM.HTTP.post(request).then(function(data) {
          console.log(data);
 })

GET Contact Roles


// Prepare the API request
var request = {
          url: "https://www.zohoapis.com/crm/v8/Contacts/roles",
          headers: {
            Authorization: "Zoho-oauthtoken 1000.XXXXXXXXXXXXXXXXXXX265bcf20e4"
          }
        };
        // Make API call 
        ZOHO.CRM.HTTP.get(request)
          .then(function(response) {
 console.log(response);
})

UPDATE Contact Roles

// Prepare the API request
        var request = {
          headers: {
            Authorization: "Zoho-oauthtoken 1000.XXXXXXXXXXXXXXXXXXX265bcf20e4"
          },
          body: {
            "contact_roles": [
              {
                "name": "Evaluator",
                "id": "5545974000000006871"
              }
            ]
          }
        };
        // Make API call 
        ZOHO.CRM.HTTP.put(request).then(function(data) {
          console.log(data);
 })

DELETE Contact Roles


// Prepare the API request
        var request = {
          params: {
            ids: "5545974000002617002"
          },
          headers: {
            Authorization: "Zoho-oauthtoken 1000.XXXXXXXXXXXXXXXXXXX265bcf20e4"
          }
        };
        // Make API call 
        ZOHO.CRM.HTTP.delete(request).then(function(data) {
          console.log(data);
 })

We hope you found this post useful. 

Let us know if you have any questions in the comments or drop us an email at support@zohocrm.com.

Cheers!

------------------------------------------------------------------------------------------------------------------------

Related Reading


------------------------------------------------------------------------------------------------------------------------
    • Sticky Posts

    • Kaizen #197: Frequently Asked Questions on GraphQL APIs

      🎊 Nearing 200th Kaizen Post – We want to hear from you! 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 #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.
    • Celebrating 200 posts of Kaizen! Share your ideas for the milestone post

      Hello Developers, We launched the Kaizen series in 2019 to share helpful content to support your Zoho CRM development journey. Staying true to its spirit—Kaizen Series: Continuous Improvement for Developer Experience—we've shared everything from FAQs
    • Kaizen #193: Creating different fields in Zoho CRM through API

      🎊 Nearing 200th Kaizen Post – We want to hear from you! 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.
    • Client Script | Update - Introducing Commands in Client Script!

      Have you ever wished you could trigger Client Script from contexts other than just the supported pages and events? Have you ever wanted to leverage the advantage of Client Script at your finger tip? Discover the power of Client Script - Commands! Commands
    • Recent Topics

    • Selling a product consisting of several components

      hi all,  I have a small issue with inventory items, I am a perfume company, and my product consists of many items,  how can I manage this, from purchase the items and convert them to be one item ready for sales  - using ZOHO platform ..
    • How to Move Behavior, Acquisition, Polls & Forms Data from Zoho PageSense to Zoho Analytics?

      Hi Zoho Community, I'm looking for a way to transfer data from Zoho PageSense to Zoho Analytics, specifically: Behavioral data (clicks, scrolls, heatmaps, etc.) Acquisition data (traffic sources, campaigns, etc.) Polls and forms data As far as I can tell:
    • [Zoho Flow] Problem using "Send document for signing"

      Hi, I get the error "Zoho Writer says \"An Internal Server Error occurred while processing this request.\"" cant understand what exactly the problem is. Any ideas? Thank you KR, Victoria
    • Fusion d'un champ image avec Writer ou Template CRM

      Il semble impossible pour le moment de fusionner dans le CRM un champ de type image vers un template. Par exemple : fusionner une image située dans le champ devis du CRM vers le template 'inventaire-devis'. Impossible également de réaliser cette opération
    • Gestion de suivi des expéditions

      Le suivi des expéditions est un élément indispensable à une gestion réussie de la chaîne d'approvisionnement. Aussi bien le fournisseur que le client peuvent bénéficier de la transparence et de la responsabilité apportées par le système ; ce dernier fournit
    • Transform Numeric Values using st, nd, rd, th or Convert Numerals to Ordinal Form - Deluge

      Please Use this sample Code This_Day_Date = zoho.currentdate.toString("dd"); value1 = "th"; if(This_Day_Date.right(1) ="1" && This_Day_Date != "11") { This_Day_Date = This_Day_Date+" "+"st"; } else if ( This_Day_Date.right(1) = "2" && This_Day_Date !=
    • How to drag and drop documents from Workdrive to Outlook

      Does anyone have an idea on how to drag and drop a document stored in workdrive into an email as an attachment in outlook? Similar to how it is possible to drag and drop documents from File Explorer stored documents straight into outlook as a static attachment.
    • Enhance Delay Configuration in Zoho Flow

      Dear Zoho Flow Support Team, We are writing to request an improvement to the delay configuration process within Zoho Flow. Currently, users are required to manually enter the exact delay duration (e.g., "2 days") in the delay block. This can be time-consuming
    • incoming email not blocked

      I am continually having to add emails and domains to my blocked list, but Still get an occasional email that is on the lists but does not get blocked. Suggestions?
    • Showing Amount Achieved Towards Target on Zoho CRM Dashboard

      I thought I'd create this post to stick a flag in the ground. My requirement: To create a visual gauge/bar chart in my CRM Sales Team Dashboard so salespeople can see their progress towards their monthly/quarterly/annual targets. The problem: After several
    • Reports for "current user"

      <Note: Topic relocated from "Start a discussion" to "Ask a question". Former post deleted.> Is it possible to specify an advanced filter for "whoever is logged in", instead of having to pick a specific user? I want to create one report the can be used by all members, but will only show data that belongs to the person logged in. When setting up the report, I want to use an advanced filter that is something like "Lead owner" "is" "${CURRENTUSER}". So the generated report will be specific to the member
    • Global Subforms

      Hey 👋🏼 We have a few subforms to calculate detailed offers for customers of car dealerships. These subforms are used in different modules and we need to create snapshots of them in different cases for documentation reasons. For example, an approved
    • Add Subform Field based on Record Field

      Hi All, I am struggling with finding a solution that can populate a subform field based on an existing field on the record. Use case is I have added Current Exchange Rate on a quote as a custom field, I then have a subform with Quoted items that include
    • Where are scheduled emails stored?

      After you schedule an email to go out through the CRM, how do you go about changing that scheduled email? Or even where can I see the list of emails scheduled to go out? They are not listed in my Zoho Mail account in Outbox which has been the only answer
    • Sheets are unbearably slow

      I'm doing some extremely simple sheets. Like 2 sheets each with 200 lines and 10 columns and a simple vlookup. ABSOLUTLY can not wait 20 secs to flip between sheets. What's up? anyone else having this trouble? Been this way for about 4 days now. Both
    • Rich text support for Notes

      Hi! Is there an opportunity to add Rich text field to Zoho CRM? We need a field that can save the HTML-formatted text in it. It's crucial for our business. Moderation Updates: The votes for supporting Rich Text for multi-line fields is captured in the
    • Colour Coded Flags in Tasks Module List View

      I really like the colour coded flags indicating the status of the tasks assigned to a Contact/Deal in the module list view. It would be a great addition to have this feature available in the list view of activities/tasks. I understand you have the Due
    • Notes formatting

      I see that I can format this idea proposal with bold, underlines , colors, and dot points even multi-level dot points However, I cannot do the same for notes in leads, contacts, potentials, etc. in CRM. This makes notes very difficult to read. PLEASE
    • Linking records from different modules

      Hello, Is there a way to link customer call records from the 'Calls' module to specific account and contact records? I've realized that our customer meeting reports are linked to both the contact and the Account records, in related list fields but the
    • Quickly send emails and sync conversations with custom email addresses in CRM

      Editions: All editions DCs: All DCs Release plan: This enhancement has been released for customers in all DCs except IN and US. We will be enabling it for IN and US DC customers soon. [Update on 22 May 2024] This enhancement has been released for all
    • Business_hour (by minute)

      Hi Zoho Team business_hours formula can only give the difference of time or day between two dates. (In the time calculation, it can only calculate the exact time. For example, it can give the difference between 16:30 and 16:55 as 0.) I want to calculate
    • At transaction level Discounts for Zoho books UAE version

      Dear Team, Please add transaction level Discounts for Zoho books UAE version. I have been requesting Zoho team past 3 years, Transaction level Discounts is a mandatory option required for our business needs. Zoho books Indian version has the option then
    • Where do Review Questions appear on the Performance Assessment?

      Hi, I want to create a Performance Assessment including only compentencies with a multiple-choice format, and a final open-text question after the competencies asking for justification of the previous objective questions. Can Review questions work for
    • Exit details not linked on employee profile

      Dear Team, The exit details that were filled in are not appearing in the employee's profile, and it seems the data is missing entirely. Please advise on how to proceed. Regards, Preetika
    • Client Script: Any plans to add support for multi-select field with onChange

      Client Script is fantastic and the documentation lists multiselect form fields as unsupported. Just wondering if there are any plans to make this a supported field. https://www.zoho.com/crm/developer/docs/client-script/client-script-events.html 2. Field
    • Versioning of Quotes and Invoices

      Would be nice if Zoho Invoice would offer the feature of saving all versions of a quote or invoice during the process - so if quotes or invoices get changed over time - a version of the old ones exist and can be reviewed and reactivated if necessary ... ;)
    • Banking - User Roles - Access To Single Bank Account

      Hi, We have different locations with each location having a specific bank account for Expenses/Etc... Can you please confirm on whether it's possible to give a user (non accountant), specific access to only a single bank account as opposed to all accounts
    • Does Zoho US Payroll now support employees in multiple states?

      Does Zoho US now support having employees in multiple US states? I looked at the site and can't find and of the restrictions on multiple states anywhere.
    • Help! Unable to send message

      Help! Unable to send message I have this email sales<at>teadvancehydraulics<dot>com, but I couldn't send outgoing email. (Reason:554 5.1.8 Email Outgoing Blocked.) Can you please help?
    • CRM Mail merge issues

      How do you configure the page on mail merge, from ZCRM??. I have written a template and structured the filters. the print preview is on one page.  I merge the document.  The merge reformats and then the document formatting moves higher and higher until by page 5 you have two half letters!!!  Very frustrating. Does anyone know if I need to insert a page break or how to correct /format this so it doesn't happen?? Help.  L
    • New notecards not syncing across devices

      Hello. I just noticed this problem happen recently. A new note being created on one device is not appearing on a different device, even though they're supposed to be synced with each other through setting it up on your account. I don't know if there's
    • Power of Automation :: Auto update a custom field based on Parallel transition under Blueprint

      Hello Everyone, A custom function is a software code that can be used to automate a process and this allows you to automate a notification, call a webhook, or perform logic immediately after a workflow rule is triggered. This feature helps to automate
    • Push error with Zoho Books and Zoho CRM

      I have successfully linked Books and CRM but I have some push errors with the following message: "The customer associated to this record is not linked to module chosen in the current contact sync configuration." I am unable to work this out, could you help please.
    • Sales Tax Rates

      Why is the Tax Customization feature limited to 2 decimal points? This issue has been mentioned several times over the last few years but it has not been changed. From a programming stand point, this should be relatively easy. Third decimal point capabilities
    • Feature Request: Ability to copy notecards to Windows desktop

      Hello, Please consider adding the ability to copy notecards to Windows desktop. Thanks!
    • Add RSS Feed Feature to Zoho Desk Communities and Knowledge Base

      It would be very useful to be able to get updates on content which is relevant to me from Zoho Desk Communities through RSS and also push my own Zoho Desk Community content to other platforms through RSS.
    • Do Individual Forums within Categories, in Desk Community, Produce Their Own RSS Feed?

      Do Individual Forums within Categories, in Desk Community, Produce Their Own RSS Feed? If not, can anyone share a work-around that could help me get an RSS feed for individual category forums?
    • Add customer to account based on domain name.

      I generate reports based on a the account field, i.e. companyX. In GoToAssist, my last provider, there was an option to automatically assign new ticket creators to a company (or account) based on their domain name. So for example, if a new employee creates
    • Zoho One Apps is not populating once clicked

      Hi Support, The Apps Menu button (corner right next to my profile) is not loading. It keeps flashing but nothing is showing up. When I type quick in the search bar to locate quickbooks, it continues to flash with no apps shown. Thanks
    • Tablet Pencil + Fillable Form

      Hi There, I just started using Zoho Writer Forms for our team on iOS. I noticed that some functions support 'scribble' or tablet pens and some do not. Is there a function I am missing where any text field can support 'scribble' or handwriting/printing
    • Next Page