Menu
subscribe our youtube channel popup

Making API Calls in Lightning Web Components (LWC) using fetch()

Lightning Web Components (LWCs) are Salesforce’s modern web development framework for building powerful, fast, and reusable components on the Salesforce Platform. However, as with any web development framework, integrating external data or services into your LWC can be a common requirement. In this blog post, we will walk through how to make API calls to third-party APIs using JavaScript fetch() method in LWC. Join us to learn about how Making API Calls in Lightning Web Components (LWC) using fetch().

Understanding Content Security Policy (CSP) in Salesforce

Before diving into the code, let’s understand a key concept that will affect your ability to make API calls in Salesforce -> Content Security Policy (CSP). CSP is a browser security feature that helps prevent malicious content from being loaded on a web page. Salesforce enforces a strict CSP, which restricts where you can make API calls from JavaScript code. By default, Salesforce only allows API calls to Salesforce endpoints (like REST API, Apex, etc.) and not third-party URLs.

To make API calls to external services, you need to first configure CSP Trusted Sites in Salesforce to allow these external URLs. This will tell Salesforce that these external services are trusted and safe to interact with your LWC.

Add Trusted URL to CSP Trusted Sites in Salesforce

Before making calls to external APIs, ensure that the API endpoint URL you want to connect to is added to the CSP Trusted Sites list in Salesforce. Here’s how you can do this:

  1. Go to Salesforce Setup: From Salesforce, navigate to Setup.
  2. Search for Trusted URLs and create a new Trusted URL by clicking on the “New Trusted URL” button. 

Fill in the API name and URL. The CSP Context content should be selected as ‘ALL’, and the CSP Directives can also be selected. I am using one of the public APIs called jsonplaceholder.typicode.com, which returns random JSON as output.

  1. Save your changes by clicking on the Save button.

Note: No need to add the API to the Remote Site Settings.

What is the fetch() Method?

The fetch() method is a built-in JavaScript function that allows you to make asynchronous HTTP requests to retrieve data from servers and it returns a Promise, which resolves when the request completes, allowing you to handle the response once it’s available.

In LWC, this method is commonly used to call REST APIs, retrieve JSON data to your Salesforce application. The Basic syntax of fetch() method as follows:

fetch(url)
  .then(response => {
console.log(‘The Response from server:’+  response.json());
}) .catch(error => {
    console.error('Error fetching data:', error);
  }); 
  • url is the resource you want to request.
  • The response is returned as a Promise, which can be handled using .then() or async/await.

The Response interface provides a number of methods to retrieve the entire body contents in a variety of different formats these are below:


Response.text(): The text() method of the Response interface takes a Response stream and reads it to completion. It returns a promise that resolves with a String. The response is always decoded using UTF-8. 

Response.json(): The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.

Response.formData(): The formData() method of the Response interface takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object. 

Response.blob(): The blob() method of the Response interface takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.

Response.arrayBuffer(): The arrayBuffer() method of the Response interface takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.

Basic Example of Fetching Data in LWC

Let’s do a basic example of how to use the fetch() method to call an API and handle the response.

Imagine you want to retrieve random data from a public API, such as jsonplaceholder.typicode.com, which returns some random data in JSON format. Here’s how you can use fetch() in LWC:

  • Create the LWC component:

First, create a new LWC component called fetchAPICmp .

sfdx force:lightning:component:create --type lwc --componentname fetchAPICmp --outputdir force-app/main/default/lwc 
  • Component JavaScript File (fetchAPICmp.js):

In this file, we’ll use the fetch() method to call the JSONPlaceholder API.

import { LightningElement } from 'lwc';

export default class FetchAPICmp extends LightningElement {

    data;
    error;

    async connectedCallback() {
        try{
            const response = await fetch('https://jsonplaceholder.typicode.com/posts')
            if(!response.ok){
                throw new Error('Network response was not ok');
            }
            this.data = await response.json();
            this.error = undefined;
            console.log('Response data is' + JSON.stringify(this.apiData));

        }catch(error){
            this.error = error.message;
            this.data = undefined;
            console.log('Error is' + error);

        }
    }

}
  • Component HTML File (fetchAPICmp.html):

Now, display the fetched data in the HTML file. We’ll show either the fetched data or an error message.

<template>
  <lightning-card title="Fetch Example" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <!-- Display the fetched data if available -->
      <template if:true={data}>
        <ul>
          <template for:each={data} for:item="post">
            <li key={post.id}>{post.title}</li>
          </template>
        </ul>
      </template>

      <!-- Display an error message if an error occurs -->
      <template if:true={error}>
        <p class="slds-text-color_error">Error: {error}</p>
      </template>
    </div>
  </lightning-card>
</template>

Explanation

The fetch() method is called in the connectedCallback() lifecycle hook, ensuring it runs when the component is inserted into the DOM.

If the response is successful, we parse the response into JSON and store it in the data property.

If there’s an error (either network-related or otherwise), it’s caught in the .catch() block and displayed to the user.

Error Handling with fetch()

Error handling is crucial when working with external APIs. While fetch() doesn’t reject the promise on HTTP error status codes (like 404 or 500), it’s essential to manually check for successful responses.

In our example, we check response.ok to see if the response was successful (status code 2xx). If not, we throw an error manually.

Conclusion

The fetch() method is an essential tool when building dynamic and interactive LWC applications. By leveraging this powerful JavaScript method, you can easily integrate external APIs into your Salesforce application, providing real-time data to users.

With proper error handling and CORS management, fetch() helps create robust applications that can handle different scenarios efficiently. Happy coding, and enjoy building with Lightning Web Components! 🙂 Hope this will help you in Making API Calls in Lightning Web Components (LWC) using fetch().

Satyam parasa
Satyam parasa

Satyam Parasa is a Salesforce and Mobile application developer. Passionate about learning new technologies, he is the founder of Flutterant.com, where he shares his knowledge and insights.

Articles: 40

Leave a Reply

Your email address will not be published. Required fields are marked *