How to use FETCH and REST APIs in Lightning Web Component | Salesforce ☁️⚡️?
Table of contents
Description
We'll see where and how to use Fetch and Rest API in LWC. There are some use cases where one is better than the other and here we'll see the difference between them.
The FETCH API is better than other APIs cause It's easy to write and simple to understand, the main reason is fetch uses promises rather than callback functions. As in Restful APIs we use callbacks to send and receive the data so, FETCH is a simpler version of XML HTTP Request.
The use of FETCH API is better because of promises only cause as an API it can send and receive the DATA throughout the application but, using promises either the data will be successful or fail so, once the promises are successfully executed in that cause we'll be getting the data and It helps the programmer to increase the scalability of the code.
It's easy to work with promises rather than callbacks cause when dealing with the async requests in case we want our result based on previous async requests and we want our API calls concerning the data we're receiving In that case promises are a huge help.
REST API
we have to create our server-side method from where we're calling our API. Then import our class in Javascript file in LWC and call from the connected callback function and parse the data cause we're getting an Array from the server. Then just store it into a variable and reflect on the UI.
To make this work we need to add the public API URL to the Remote Site Settings
- APEX
public with sharing class APICalloutREST {
@AuraEnabled
public static string getRandomCat(){
http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.thecatapi.com/v1/images/search');
req.setMethod('GET');
HttpResponse res = http.send(req);
return res.getBody();
}
}
- JS
import {
LightningElement,
track
} from 'lwc';
import getRandomCat from '@salesforce/apex/APICalloutREST.getRandomCat';
export default class APICalloutREST extends LightningElement {
@track imageURL;
connectedCallback() {
this.getRandomCatRestJS();
}
getRandomCatRestJS() {
getRandomCat({})
.then(result => {
var resParsed = JSON.parse(result);
this.imageURL = resParsed[0].url;
})
.catch(result => {
console.log('catch is running ' + result);
})
}
}
- META
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
FETCH API
In FETCH API we don't use server-side functionality all the things are done in a Javascript file, inside the connected callback we've used promises to get the data and store it in the track variable and reflect it on the UI.
To make this work we need to add the public API URL to the CSP Trusted Sites (Content Security Policy Trusted Sites)
- JS
import {
LightningElement,
track
} from 'lwc';
export default class APICalloutFETCH extends LightningElement {
@track imageURL;
connectedCallback() {
this.getRandomCatFetchJS();
}
getRandomCatFetchJS() {
fetch("https://api.thecatapi.com/v1/images/search", {
method: "GET"
})
.then(result => result.json())
.then(data => {
console.log('DATA::>>', data);
this.imageURL = data[0].url;
});
}
}
- HTML
<template>
<lightning-card title="Random Cat Images from FETCH API">
<img src={imageURL} />
</lightning-card>
</template>
- META
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
Here we've just used the GET method soon we'll see how to use the POST method on REST & FETCH APIs.
You can have this code from ---> Click Here