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

    • [Product update] Instagram Profiles Integration with Zoho Analytics

      Dear Customers, We want to inform you about an update affecting the Instagram Profile integration with Zoho Analytics. Meta is deprecating the "Impressions" and "Plays" metrics as per their announcement in this change-log document. To ensure uninterrupted
    • how to prevent some user to choose the stage in deal module when creating a deal record?

      I want to prevent some users to choose a deal stage when creating a deal record I want some users to follow the pipeline from top to bottom. can I do that? because it seems I can't hide this field . is there any workaround for this? can I hide it using
    • Quotes: Export to PDF and attach using API

      Hello, I would like to automate the following: - create a Quote for an account - export that quote to PDF - upload the PDF back into ZohoCRM, as an attachment for that Quote using API methods. Is this possible, has anybody done this before? Thank yo
    • Zoho CRM Contact Form style in website

      Hello, I am trying to embed the Contact Form from Zoho CRM into our existing WordPress website to replace our current contact form. The look on the website is not similar to the 'Preview' when I am setting up the form in the CRM, and I have limited html
    • RTL Support for Webforms in Zoho CRM

      Dear Zoho CRM Support Team, We are writing to request an enhancement to the webform builder functionality within Zoho CRM. Currently, to create a webform in a right-to-left (RTL) language, the entire CRM instance must be set to RTL, which can be inconvenient
    • Data Sync

      Hi, is there any scope for live data synchronization with CRM and Analytics, especially as TV channels for motivator is unable to provide charts, dashboards within Analytics seems the obvious solution?
    • I have integrated WhatsApp but it in vissible to sent message to customers

      I have integrated WhatsApp but it in vissible to sent message to customers.
    • Embedding SalesIQ in Zoho Creator within a (Internal) Widget - Not customizable

      I've been trying to integrate SalesIQ within an application in Zoho Creator. And since <script> tags can't be rendered within the HTML snippet, I've created a separate widget which is hosted internally (through packed .zip file) and added SalesIQ through
    • Zoho Campaigns - how to have distinct Lead and Contact segments?

      Hi, I have been using Zoho Campaigns for quite a while now. What is not clear to me is how to have distinct segments for Leads and Contacts. I tried and used filters to do the trick, but that doesn't always work as I expect. For instance, converted Leads
    • OAuth Error - {"error":"invalid_code"}

      curl -v --ipv4 -X GET \ --url 'https://accounts.zoho.com/oauth/v2/auth?response_type=code&client_id=[CLIENT_ID]&scope=AaaServer.profile.Read&redirect_uri=https://my-real-domain.com/zohocallback.xhtml&prompt=consent&access_type=offline' RESPONSE Location:
    • Zoho Campaigns Pop Up not scaling properly on phone browser

      The pop up for the sign up for my mailing list works fine on my browser on PC, but on phone, it only shows half of the pop up. How do I fix this?
    • 📣📣 Zoho Bookings - Feature Roadmap 2024

      Hi Everyone, Thank you for all the support you have been showing Zoho Bookings. We had a fabulous 2023, with a bunch of new features and over 60K new users. In 2024, our prime focus will be on user experience, and we have a few vital features coming in
    • Cannot add Outlook Calendar to Zoho Bookings

      Hello, When I try to add my Outlook Calendar to Zoho Bookings I get almost to the end, including accepting the permissions and authorising the Office 365 account then I get the error message "Something's not right on our side. Sorry about that. Please
    • booking link that expires

      I have a suggestion that is  crucial. When i send booking URL to clients they keep the link and they book appointment whenever they want multiple times. You should give us the Booking URL feature. We should be able to send it and the user can use it only
    • Bookings - How do you select more than 1 service?

      Hello - I'm setting up a client with CRM and Bookings. She is a beautician that needs to have people book more than 1 service at time. Some services are add-on and she wants to collect a deposit but not the full payment.  How do we allow the clients to book more than 1 service at a time? Can the system take partial payments?
    • Canvas: is it possible to have a fixed header?

      Hello. Does Canvas provide the option to have a fixed header, similar to the standard view? It would also be interesting for other parts of the interface, like the header or sidebar of the tab section. Thanks!
    • A couple of minor enhancements to Workflows

      Last updated on September 17, 2024: These enhancements were initially available for early access, and we've now enabled them for all users. We are elated to announce a couple of enhancements to custom functions in our Workflows! Say hello to: "Source"
    • Introducing ICR in Zoho CRM: Transform your printed text into digital data

      From writing on papyrus in the ancient times to creating a humble record in your CRM, the world may have evolved with how it used to record data, but data entry as such has not been simplified. It is still a repetitive and arduous chore on which businesses
    • Auto-Generate & Update Asset Serial Numbers using a custom function (Assets Module)

      Hello Team, I’ve been working on a script to automate one of our processes in Zoho FSM, and the core functionality has been successfully implemented. However, I’m encountering an issue related to serial number allocation, which is not working as expected.
    • Linking Reports and Projects to CRM Portal

      Is there a way to link reports and projects to a CRM portals?
    • How to filter deals for anything not yet delivered

      Hello I want to be able to filter my deals for anything where the Sales Order is not delivered. I'm stuck because I want to include deals with and without Sales Orders, and just exclude ones with an associated Sales Order which is stage Delivered Does
    • Currency fields and decimal places in CRM email templates

      Hi, How do I get more than the standard 2 decimal places showing in a Currency field, on an email template? In the Layout for my Currency field, it is set to 6 decimal places. I want to show up to 6 places in the email template (unrounded). See attached
    • Package Dimensions

      Packages need to have dimensions that are sent to carriers in addition to just the weight. Without the package dimensions being transmitted to carriers, the correct dimensional weight is not calculated for the label price, which results in corrections
    • Zoho One for Multiple Organisation under a Parent Company

      Dear Zoho One, We are a two companies running different business (service and sales) in Malaysia, with our parent HQ in Germany, and we have multiple sister companies scattered across the region of Asia.  Currently, our malaysia branch is using Zoho CRM and are in the process of upgrading our accounting system with Zoho One. However, there is one huge problem, and that is Zoho Apps does not allow us to run multiple organisations with a single subscription. This is our only deal breaker at the moment/
    • Track All Emails from Company Domain

      For our business model, it's almost impossible to keep track of all emails sent to clients, under the way ZohoCRM currently tracks emails to customer records via the user account only. We'd like to see a way of tracking emails via domain only, separate
    • 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
    • Workable tutorials on Zoho RPA sorely needed - who can share?

      Hi folks, I own several RPA tools and would love to switch to Zoho RPA just to keep everything in the same ecosystem. However, Zoho RPA documentation lacks examples of how to do the most basic activities where RPA is most common. In particular: 1. opening
    • Need head start/ideas for a new application using the portal

      Hi, I am just looking for ideas, or direction, about a new app. Simply put, I have multiple vendors offering products, and multiple customers buying those products. BUT the administrator controls the product offering and prices. For example, Vendor "A"
    • SMTP zoho email + prestashop problem

      Hi,  i just created an email for my domain with an e-shop built on prestashop... however, after setting the SMTP (myemail@mydomain.com, password is correct, server is smtp.zoho.com, port 465, SSL) i still get an error message saying i should check my settings. with gmail address it works fine, but zoho has a problem.. anybody encountered this problem, or has any idea or solution? thanks a lot.
    • Cannot paste consistently

      When authoring and editing articles in Zoho Learn, I often find that I am unable to paste content. Some days, Zoho will let me paste a few times using keyboard shortcuts (Ctrl-V), but then will randomly stop allowing this function.  I have also tried
    • Recording stripe fees for sales w/out invoices

      In my business, people make many purchases w/out an invoice using a credit card. With invoice payments, I record them as sales and deposit the $ to credit card clearing, deduct stripe fees associated on the bank fees line, and then I record the stripe
    • Fields from Zoho CRM not appearing in merged document

      Hi, I have a custom CRM module where certain fields are looked up from "Contacts". When I then try to run a mail merge from my custom module, the date from the fields which were fetched from contacts do not appear in the document. I just see the field
    • Going back to older version

      Hi, One of our tech did a new version of our app, but created problems that we do not have time to repair, we just want to go back to an older version for the moment. To make sure we choose the right older version, we also want to double-check the dates
    • Zoho Creator HTML Page

      Hello Team, I have a query related to the HTML page I created in Zoho Creator. I would like to apply some filters on this page without passing them through URL parameters. Could someone please guide me on how this can be achieved? Thanks & Regards, Piyush
    • Remote Assist Reboot - User can't login

      Last night one of our support agents was using Zoho Assist doing a remote assist session.  A reboot was required. Upon rebooting the Windows 10 user says he can't login and that he is getting an invalid password error.   Is this a known problem? Any thoughts?  Awaiting customer to arrive at work today to attempt safe mode boot.
    • Move a ticket from one department to another without creating the product in both departments

      Hello everyone, I am having serious problems with the products. When a customer creates a ticket in a department and selects a product by mistake and we move it to the corresponding department it automatically creates in both departments the product.
    • How do I setup product syncing between Desk and CRM?

      How do I setup product syncing between Desk and CRM? I can see in Desk where to add products, but it doesn't show the existing products I imported into CRM. Where do I turn on the syncing? I assume there's an option somewhere similar to the option to
    • multiple users unable to view campaigns

      I have just added two users to zoho campaigns.  when they log in they don't see the details regarding the email campaigns already run.  i would like all users to access this.
    • If a contact is deleted from Zoho CRM, will all related activities be deleted related to the contact?

      I think question is clear.
    • Factur-X

      Bonjour, J'ai découvert dans la dernière release notes de Zoho Books, l'apparition du support du format Factur-X (Export Transactions in Factur-X Format | Help | Zoho Books), mais il faut apparemment activer une nouvelle fonctionnalité de taxes. Quelqu'un
    • Next Page