Fetch APIs How and Where to use it in Lightning Web Component Salesforce | LWC Stack ☁️⚡️

 In this blog we are going to talk about fetch APIs. We will learn following things in this blog - 

✅ What is fetch API

✅ How and When to use it in LWC

✅ Handle requests using Promises

✅ Side by side comparison with REST APIs


When JSON was not that much popular the primary format of data exchange was XMLHttpRequest()

It is a javascript function that made it possible to fetch data from APIs. But why I am talking about XMLHTTPRequest instead of fetch ?

It is because the fetch api is a simpler and easy to use version of XMLHttpRequest. Like all APIs, the fetch api is used for sending and receiving data between applications.

The major difference is between other APIs and fetch is that fetch works with promises, not callbacks.

With a promise it is easy to write and handle async requests. For example in a async request the word async means 'Take some time to execute not right now'

So if you have to perform actions based on the returned response or you want to execute the functionality based on promises in a particular order then you may use fetch api.

Fetch only throws an error if the request itself is interrupted. To handle 400 and 500 responses, you can write custom logic using ‘response.status’.

The ‘status’ property will give you the status code of the returned response. 


Please check the code below for a basic fetch request example and side by side comparison with rest APIs.

For other examples you may refer these official documentation 

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

https://javascript.info/fetch-api


Example -1 : Getting the data using REST APIs

Add the URL in Remote Site Settings


getRandomCatRest.html

1
2
3
4
5
<template>
  <lightning-card title="Get Random Cat using REST APIs">
    <img src={imageURL} />
  </lightning-card>
</template>


getRandomCatRest.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { LightningElement } from "lwc";
import getRandomCat from "@salesforce/apex/getRandomCatImage.getRandomCat";

export default class GetRandomCatRest extends LightningElement {
  imageURL;
  connectedCallback() {
    getRandomCat({}).then((response) => {
      console.log("###Response : " + response);
      var parsedData = JSON.parse(response);
      this.imageURL = parsedData[0].url;
    });
  }
}


getRandomCatImage.cls

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public with sharing class getRandomCatImage {
    
    @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 resp = http.send(req);
        return resp.getBody();
    }
}


Example - 2 : Getting the data using fetch APIs

Add the URL in CSP Trusted Sites



getRandomCatFetch.html

1
2
3
4
5
<template>
  <lightning-card title="Get Random Cat using FETCH APIs">
    <img src={imageURL} />
  </lightning-card>
</template>


getRandomCatFetch.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { LightningElement } from "lwc";

export default class GetRandomCatFetch extends LightningElement {
  imageURL;

  connectedCallback() {
    fetch("https://api.thecatapi.com/v1/images/search", { method: "GET" })
      .then((response) => response.json())
      .then((data) => {
        console.log("🚀 ~ data", data);
        this.imageURL = data[0].url;
      });
  }
}


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

5 Comments

  1. can you please create something from https://jsonfaker.herokuapp.com/users

    ReplyDelete
  2. can you please create something with https://jsonfaker.herokuapp.com/users

    ReplyDelete
  3. for some reason, at first when created Rest API , the image was not visible to me but when I created CSP Trust sites record , it was working fine for me

    Suggestion : please create remote site setting and CSP trust sites first and then create LWC component and add it to the lightning page.

    Thanks, Kapil for the insight on Fetch API , Kudos (Y)

    ReplyDelete
    Replies
    1. Hi Himanshu, thanks for your inputs here.
      It will help others :)

      Delete