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

6 Comments

  1. hi
    i do it on correct way but its showing [Failed to fetch] error on the record page ..

    ReplyDelete
    Replies
    1. Have you added it in CSP trusted sites ?

      Delete
    2. yes i add & i use same code but its showing error Failed to Fetch.

      Delete
  2. Refused to connect to 'https://icanhazdadjoke.com/' because it violates the document's Content Security Policy.

    ReplyDelete
    Replies
    1. hi Sai You have to it on correct way Like This https://icanhazdadjoke.com than save

      Delete
  3. fetch() will be rejected by eslint. you need to use XMLHttpRequest();

    ReplyDelete