Today, we are going to understand how we can make callouts directly from LWC. In Salesforce, we only use Apex to make calls to an external system for Integration. But in some scenarios, we are not able to make callouts in Apex like you are uploading a large-size file. So, you are using LWC in the front end & getting the content in JS, and then passing the content of the file as a string in apex. It will give you an error of Heap Size Limit.
In those scenarios, We need to make callouts directly from JS. So, It will work perfectly for your different scenario. Let's go in-depth and understand how can we make callouts:
Firstly, We need to set up a CST Trusted Site definition in Salesforce.
Also Read: Connect Dropbox with Salesforce using REST API
CSP Trusted Sites
CSP stands for Content Security Policies. CSP is a way to implement the W3C standard to the page. To allow Fetch API to make a callout to a remote server we need to add the endpoint as CSP trusted sites. We need to add the base URL of the API endpoint to the Trusted Sites in the salesforce setup.
We will use the free public ChunkNorries.io that returns random chunk jokes.
Step 1: Go to Setup, search for trusted and Click on CSP Trusted Sites.
Step 2: Click on the New Trusted Sites. Fill in all the related details and Click Save.
Now, We are ready to use Fetch API in LWC. Create an LWC Component and make it exposed for Home Page.
chunkNorriesAPI.html
chunkNorriesAPI.js
chunkNorriesAPI.js-meta.xml
Done! Deploy your component and display the LWC on Home Page. Let's check the output:
Click on the Generate Random Chunk Jokes button and you will get a new joke every time you click.
Summary:
We implemented a callout from LWC using Fetch API. This code is not ready for production because no error handling was implemented. This is only for a demo purpose.
Also, The API which we used is a public API without any Authentication. I will explain to you how you can do the same callout with private APIs in LWC in the next blog. In that, I will take a scenario of file uploading in dropbox.
Thanks for reading. Still, if you have any further suggestions, thoughts, and questions, then just make sure to comment down.
Comments