Harshit Saxena
Locus Coder

Locus Coder

How to use FETCH and REST APIs in Lightning Web Component | Salesforce ☁️⚡️?

Harshit Saxena
·May 21, 2022·

3 min read

How to use FETCH and REST APIs in Lightning Web Component | Salesforce ☁️⚡️?

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Description
  • REST API
  • FETCH API

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

Screenshot 2022-05-22 at 1.14.21 AM.png

  • 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>

Screenshot 2022-05-22 at 12.50.38 AM.png

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)

Screenshot 2022-05-22 at 9.14.02 AM.png

  • 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>

Screenshot 2022-05-22 at 1.03.12 AM.png

Here we've just used the GET method soon we'll see how to use the POST method on REST & FETCH APIs.

Screenshot 2022-05-22 at 10.18.51 AM.png

You can have this code from ---> Click Here

Did you find this article valuable?

Support Harshit Saxena by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this