Fetch APIs - NASA's Astronomy Picture of the Day in Lightning Web Component Salesforce


 In this blog I will show you an example of using Fetch APIs in Lightning Web Component Salesforce.

What are Fetch APIs ? - The Fetch API is a JavaScript interface that makes it easier for developers to fetch data from servers and interact with APIs. It's a modern alternative to XMLHttpRequest, and it uses JavaScript Promises to make requests from web browsers.

It's a feature that allows you to make HTTP requests (such as GET, POST, PUT, or DELETE) to a web server.

As an example we will be calling APOD - Astronomy Picture of the Day API of NASA to get the image from their server.

API urlhttps://api.nasa.gov


Step 1 : Add the API URL in Remote Site Settings (Setup --> Remote Site Settings) as shown below


Step 2 : Add the API URL as a Trusted URL (Setup --> Trusted URLs) as shown below



Step 3 : Add the response data URL that needs to be used in the image tag to display the image as Trusted URL as shown below



Step 4 : Please check below LWC

HTML

1
2
3
4
<template>
  <lightning-card title="APOD(Astronomy Picture of the Day)"> </lightning-card>
  <img src={imageURL} />
</template>


JS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { LightningElement } from "lwc";
import apiKey from "@salesforce/label/c.NASA_APOD_APIS";

export default class APODAPIs extends LightningElement {
  imageURL;
  apodDate;
  connectedCallback() {
    this.apodDate = "2024-09-14";
    fetch(
      "https://api.nasa.gov/planetary/apod?api_key=" +
        apiKey +
        "&date=" +
        this.apodDate,
      {
        method: "GET"
      }
    )
      .then((response) => response.json())
      .then((data) => {
        console.log("🚀 ~ data:", data);
        this.imageURL = data.hdurl;
      });
  }
}


Output


Checkout the Complete 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