REST Callout from Lightning Web Component Controller | Salesforce | LWC Stack ☁️⚡️

 In this blog I will share the build to make a simple REST callout using Lightning Web Component Controller.

We will use a sample third party domain to do the callout.

We won't be using APEX code it's just pure JavaScript and HTML.


Rest Callout domain : https://icanhazdadjoke.com/


Configuration

You have to add your domain in the CSP Trusted Sites setting in your Salesforce org to make a successful callout as shown below : 



Now you may follow the code below : 


RestTest.html

1
2
3
<template>
  <center><p style="font-size: xx-large">{randomJoke}</p></center>
</template>


RestTest.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { LightningElement } from "lwc";

export default class RestTest extends LightningElement {
  randomJoke;
  connectedCallback() {
    const calloutURL = "https://icanhazdadjoke.com";
    fetch(calloutURL, {
      method: "GET",
      headers: {
        Accept: "application/json"
      }
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
      })
      .then((responseJSON) => {
        this.randomJoke = responseJSON.joke;
      });
  }
}


Output



Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments