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

    • Sharing my portal URL with clients outside the project

      Hi I need help making my project public for anyone to check on my task. I'm a freelance artist and I use trello to keep track on my client's projects however I wanted to do an upgrade. Went on here and so far I'm loving it. However, I'm having an issue sharing my url to those to see progress. They said they needed an account to access my project. How do I fix this? Without them needing an account.
    • Zoho Campaigns Forms not Responsive on Website

      I have a mobile responsive Zoho Sites website and when I add a Zoho Campaigns form, it is not responsive. I have used the website code and ensured that the 'responsive' checkbox is selected. But, the form is not responsive to mobile. I have attached a
    • Oldest mail on top?

      I am old, and probably missing something simple, but how do I flip my zoho mail so oldest mail is on top?  Thanks in advance, and a HUGE thank you to the entire ZOHO team.  You just keep getting better!
    • Desk API to add or change commenterId to a comment

      Please let me know how to add comments on tickets for different agents using the API. When adding a comment it will take commenterId but then ignores that and used the API agentId. Did not see in API docs which values are readonly. I pleased to see commentedTime worked for past times. Regards, Glenn
    • How send a ticket attachment using the Sendreply API in Zoho Desk

      API document references : you make use of the Upload file API and gather the attachment ID. This ID is be passed with the Send email Reply API to deliver responses with the attachment intact. Code template is as below: // ORGID ORGID = "XXXXXXX"; // Masked
    • First Insight - Find your Fields

      The Wheels of Ticketing - Desk Stories Find your Fields What are fields? Fields are crucial in ticketing modules that capture information about Tickets, Customers, Organizations, Products, and more. Depending on the kind of data being stored, users can
    • Automation#30: Auto-Update Time Entry to the Nearest 5 Minutes

      Hello Everyone, Time tracking is a feature in Zoho Desk to help businesses stay organized and efficient. For Zylker Techfix, this feature has helped to track the duration of gadget services to generate accurate bills. However, Zylker Techfix faced a unique
    • Email adding to existing ticket

      hello Is there some syntax i can add e.g. to the subject line / body of my email that when it reaches the Zoho portal will add the request to an existing ticket. e.g {123} Currently if i have an open ticket and a customer emails me direct, i then forward
    • How to define different shift timings for each weekday in Zoho People?

      Hi everyone, We’re using Zoho People for attendance tracking and need to configure a standard 39-hour workweek that is structured like this: Monday to Thursday: 8 hours per day Friday: 7 hours Currently, our service provider has set up the workweek as
    • add two date range

      Hi, How can I add two date range selections to compare two different column values in a single pivot view? I have attached a snap for your reference.
    • Announcing new features in Trident for Windows (v.1.26.5.0)

      Hello Community, Trident for Windows is here with exciting new features to elevate your email communication and enhance productivity. Let’s dive into what’s new! Open .eml files in Trident. You can now open .eml files directly using Trident. This makes
    • Adjust The max character in Specification Field

      Is there another way to adjust the maximum character limit for the Specifications field in Zoho Commerce? I need to accept responses with fewer than 200 characters.
    • Customize the Sign In And Sign Up in Zoho Commerce

      Is there another way to customize the Sign In and Sign Up in website Zoho Commerce like this i want to customize to edit it like change the "Sign In" word into "Login Zoho Commerce" it is possible or other way to do that?
    • Territories : Deluge and APIs

      I am trying to work out how to filter a deluge query by territory eg "SELECT Total_Amount, Stage, Closing_Date, Created_Time, Deal_Name FROM Deals WHERE Stage in (" + varBaseCriteria + ") AND Territory = 'Territory1'" The problem being that Territory
    • Tidying up messes file system on Site

      I'm been given access to a new site that's been managed by several different people over the years, each with different ways of managing images and files. If I move an image from one folder to another, it shows a missing image icon on the site's page.
    • Move Archive Button in Zoho Mail to Main Toolbar?

      Is there a way to add the Archive Button to this tool bar so I don't have to click the three dots every time?
    • Introducing Bigin 360: Our new pricing edition with increased feature limits and pre-installed toppings

      Dear Biginners Club, Today, we're pleased to launch a brand-new pricing edition called Bigin 360, our highest pricing edition that will sit on top of Express and Premier editions. It's been over four years since our launch, and we're receiving some great
    • URL field display value

      Is it possible to give a URL stored in a project a display value, rather than showing the whole url? I have a lot of projects connected to issues filed on a separate site, each with a distinct URL. For example: https://bugs.koha-community.org/bugzilla3/show_bug.cgi?id=40000
    • need payment link excl. TDS Amount.

      Dear Team Zoho, Kindly generate a payment link excluding TDS amount. So that TDS can be submitted through portal. Thanks & Regards, Arijit S.
    • CRM is very slow now

      CRM is very slow now. Plz check ASAP
    • Access error when running invokeurl

      Hi, I'm running the following code: string standalone.test_api() { LoroToken=zoho.crm.getOrgVariable("LoroToken"); info "LoroToken:"+ LoroToken; headersMap = Map(); headersMap.put("Authorization", "Bearer "+LoroToken ); headersMap.put("Content-Type",
    • Disable Column Freeze in PWA View but Keep It on Desktop — Zoho Creator Reports

      Zoho Creator offers a useful feature to freeze up to two columns in a report view, which works well on desktops. However, our users access the app on both laptops and mobile devices, and freezing columns makes reports nearly unusable on smaller screens.
    • How do I add more space to a note in ‘draw’?

      I’m taking handwritten notes using the draw note, but I don’t seem to be able to scroll down to get more room on the page. How do I make more room to take notes?
    • Overtime per week vs. per day

      In the United States 90% of the states calculate overtime as working more than 40 hours per week. It appears that Zoho People can only calculate overtime per day.  How do we fix this? Here is an example: Mon      8 hours Tues      7 hours Wed      9 hours Thur      8 hours Fri            8 hours -----       Total      40 hours (no overtime) However, Zoho people says 1 hours of overtime because the employee worked 9 hours on Wednesday. Maybe I have something setup wrong in Zoho People?  
    • Add Hebrew Language Support in SalesIQ Idle Chat Handling and Reminders

      Dear Zoho SalesIQ Team, Greetings. We would like to request the addition of Hebrew language support in the Idle Chat Handling and Reminders functionality within Zoho SalesIQ. 🗣️ Background & Use Case Currently, we have successfully configured our Zobot
    • notebook synchronization - problem

      Good afternoon, Since yesterday when trying to create a new notebook, it does not let me and when creating the notes they are not synchronized with the cloud, I think the error may be with the encryption of images because in the pages appears the image
    • Notebook 3.5.0 -- Sort order Name A-Z not working

      Just updated to Notebook 3.5.0 on Windows 10. Sort order by Name, A to Z is backwards, like Z to A. Selecting Z to A still works as expected.
    • Stay organized with chat-to-ticket timers

      Hi there! Ever lost track of a customer’s message? Or found yourself scrolling through long chat threads trying to figure out what’s what? Setting up a chat-to-ticket timer can help. It decides when a reply should stay in the old ticket or create a new
    • New notecards not syncing across devices

      Hi, I'm having the same problem where my notes are not syncing from my Android to my laptop. Please help
    • Please add custom sort in Windows ver. of Notebook!

      Dear Zoho, I love the custom sort (drag and order notes) in the Android version of Notebook, but when I sync onto the Notebook on Windows, the note orders all get messed up because it doesn't support custom sorting yet. This makes it impossible to do
    • Formula to return string "WK 26 - 6.2.25 - 6.8.25

      Here's what I've got but syntatic failure: if(not(isnull(${Deals.GS_Due})), "Week " + Tostring(ceil(dayofyear(${Deals.GS_Due}) / 7)) + " - " + Tostring(month(${Deals.GS_Due})) + "." + Tostring(day(${Deals.GS_Due})) + "." + Tostring(year(${Deals.GS_Due}))
    • Introducing LeadChain in Bigin to sync leads from Social Ads easily

      We're excited to introduce a new topping in Bigin called LeadChain by Zoho Social. LeadChain instantly syncs lead information from social media lead ads to Bigin, making it easier to turn them into customers. It also helps you send conversion data back
    • Templates Access

      There should be an option to grant users access to templates but not allow them to edit/delete templates. In setup there is only one tick option for templates. This will give any user access to view as well as delete/edit. This doesnt make sense as they
    • Generate a Zoho Sign link

      From time to time I get a response "I never received your you e-document for electronic signature" is there a way to generate a Zoho Sign link to share.
    • Power of Automation :: Autocomplete the Project upon Task closure.

      Hello Everyone, A Custom function is a user-written set of code to achieve a specific requirement. Set the required conditions needed as when to trigger using the Workflow rules (be it Tasks / Project) and associate the custom function to it. Requirement:
    • Unable to send email through Gmail

      So I had a custom domain email from Zoho and I was able to send emails from this account through my gmail. 2 days ago I added another user. This user is not able to receive any emails, that's the first issue, moreover, even though I haven't changed anything else other than adding this user, now I am unable to send email through my gmail account with the first user either! I have opened a case with priority "I am stuck, need assistance", haven't got a single reply in about 36 hours. I am unable to
    • "Invalid Credentials(Failure)" when configuring IMAP (Outlook)

      Getting the below response when attempting to configure Zoho mail in Outlook 2016: Notes (what I've done so far): Zoho mail on web client is working with no issues. Though I was certain the username & PW were correct (was using same credentials on web client as I was attempting to utilize in Outlook 2016), just in case, I went ahead and changed my password on the web client and re-attempted Outlook configuration; same error response. IMAP for my email account was enabled on the web client (and POP
    • Custom service report or Zoho forms integration

      Hello, So far the experience with Zoho FSM and the integration with Books has been good, however there are limitations with service reports. As with my business, many organisations send technicians to different types of jobs that call for a different
    • Pre-fill Email field on Zoho Forms

      Hello there, How do we automatically pre-fill the email address field of a Zoho Form from the data that is in CRM? Thanks, Joel
    • Webhook Trigger for New Messages in Cliq Channels

      Hello, I would like to request a feature to enable webhook triggers when a new message is added to a Cliq channel. This functionality would allow us to seamlessly send important information from Cliq to other relevant systems. This webhook trigger can
    • Next Page