Make REST API Callout Using Lightning Web Component in Salesforce

While working with Salesforce Lightning Web Components, I needed to fetch real-time currency conversion rates for a client project to convert opportunity amounts into various currencies based on different geographic locations. For this, I used a REST API callout to fetch the data from openexchangerates.org and enable accurate currency conversion.

In this Salesforce tutorial, we will learn how to make a REST API Callout using Lightning Web Components.

REST API Callout Using Lightning Web Component in Salesforce

To make a REST API callout, we have two main approaches:

  1. Using the Fetch API: The Fetch API is a JavaScript interface that allows us to make HTTP requests directly from web browsers. It’s an easy-to-use and efficient way to interact with RESTful services, providing promises and better support for handling asynchronous tasks.
  2. Using an Apex Class: For complex use cases when server-side processing is needed, we can use an Apex class. This method allows us to call external REST APIs from the Salesforce server and handle authentication, headers, and other configurations.

Both methods have their use cases, with the Fetch API usually being used for client-side operations in a Lightning Web Component (LWC), and Apex is preferred for server-side callouts where additional security and processing are required.

REST API Callout Using Fetch API in LWC

In this approach, we’ll use the Fetch API within a Lightning Web Component to perform a REST API callout directly from the client-side. This method is suitable for scenarios where the external API supports CORS (Cross-Origin Resource Sharing) and does not require secure server-side authentication.

The fetch API makes the call from the client-side (browser), so Salesforce uses Content Security Policy (CSP) to control which domains are allowed.

In the example below, we will use the open API https://poetrydb.org from which we can fetch the data using the REST API Callout. Using this API, we will display quotes in the LWC component.

Register the URL of the external API in the CSP Trusted Site

To allow the URL of the external API, register it in the CSP trusted site following the steps below.

  1. Navigate to setup > Remote Site Settings > New Remote Site.
Make API callout in Salesforce
  1. Enter the name for the Remote Site Name, and in the Remote Site URL, enter the URL of the external API. Here, we are using the API URL https://poetrydb.org.

After this, select the Active checkbox and click Save.

Rest API callout using fetch API in LWC

Create the Lightning Web Component for the REST API Callout

After registering the API in the trusted Salesforce, Salesforce security will allow the data from the source API.

Now, follow the steps below to create the Lightning Web Component in which we will use the fetch method to call out the REST API.

  1. Open the VS Code IDE integrated with your Salesforce org. Create a Lightning Web Component with the name quoteFethcer.
  2. To make a callout for the REST API the logic will be handled in the JS file. Enter the code below in the JS file.
import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class QuoteFetcher extends LightningElement {
    @track quoteReady = false;
    @track quote = '';
    @track author = '';
    @track loadingSpinner = false;
    @track error = '';

    handleClick() {
        this.quoteReady = false;
        this.loadingSpinner = true;
        this.error = '';
        fetch('https://poetrydb.org/title/Ozymandias/lines.json', { method: 'GET' })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP error: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                this.quote = data[0].lines.join('\n'); 
                this.author = 'Percy Bysshe Shelley';
                this.quoteReady = true;
                this.loadingSpinner = false;
            })
            .catch(error => {
                console.error('Fetch Error Details:', error);
                this.error = this.getErrorMessage(error);
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error Fetching Poem',
                        message: this.error,
                        variant: 'error'
                    })
                );
                this.loadingSpinner = false;
            });
    }

    getErrorMessage(error) {
        if (error instanceof TypeError) {
            return 'Network error: ${error.message}. Please check API availability or CSP settings.';
        } else if (error.message.includes('HTTP')) {
            return 'Failed to fetch poem: ${error.message}';
        }
        return 'Unexpected error: ${error.message}';
    }
}
  1. After this, enter the code below in the HTML file to define the UI of the LWC component.
<template>
    <lightning-card title="Display Poetry" icon-name="custom:custom14">
        <lightning-layout class="quote-layout">
            <lightning-button
                label="Get Poem"
                onclick={handleClick}
                class="fetch-button">
            </lightning-button>
            <div class="slds-p-around_small">
                <template if:true={loadingSpinner}>
                    <lightning-spinner alternative-text="Loading" variant="brand" size="medium"></lightning-spinner>
                </template>
                <template if:true={quoteReady}>
                    <div class="quote-container">
                        <p class="quote-text">{quote}</p>
                        <p class="quote-author">— {author}</p>
                    </div>
                </template>
                <template if:true={error}>
                    <div class="slds-text-color_error">{error}</div>
                </template>
            </div>
        </lightning-layout>
    </lightning-card>
</template>
  1. To make the component visible to the Lightning page, enter the following code in the meta.xml file.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Deploy the Lightning web component to the Lightning page. In the component’s UI, you will see a button that calls the method handleClick(). This will display the data fetched from the API poetrydb.org in the LWC component.
Make rest API callout in Salesforce Lightning Web Components

This way, we can make a REST API callout in Salesforce Lightning web components using the Fetch API method.

REST API Callout Using Apex in LWC

To call an external RESTful web service (REST API) from a Salesforce Lightning Web Component, we can also use an Apec controller class.

In this method, the Apex controller handles the server-side logic. The flow of calling REST API using apec goes like LWC calls Apex method > Apex sends HTTP request to external REST API>API responds to Apex>Apex returns response to LWC>LWC processes response and updates the UI.

In this example, I will use the open API “Sentiment Analysis” and make sure to use the URL that I have mentioned below. The one I used from the other resources was broken and did not return any data.

The updated URL to use the Sentiment analysis API is :

https://salesforcelwc.herokuapp.com/sentiment

How Does a Sentiment Analysis API Work?

The API for sentiment analysis uses POST and GET requests to communicate with the service. JSON-formatted responses are returned in the request body. Sentiment analysis uses artificial intelligence (AI) technology, specifically, natural language processing (NLP) to analyze text. In addition, text analysis techniques and linguistics help determine the sentiment of the text.

Register the URL of the external API in the Remote Sites

To make a REST API callout through Apex, it is required to register the API url in the remote sites.

Navigate to the Setup> Remote Site Settings. Click on the New button, in the next window, enter the Site Name and URL.

Ensure to select the Active checkbox and lastly click on the Save button.

Rest API call using Apex in Salesforce

This registers the API as a trusted URL that allows it to be accessed within the Salesforce org.

Create the Apex Class and Lightning Web Component For the API Callout

To make a REST API callout using the Apex in the Lightning web component, we first need to create an Apex class.

In the steps below, we will first create the Apex class, then we will create the Lightning web component.

  1. Create an Apex controller class, SentimentAnalysis, and enter the code below defining the logic to make a REST API call.
public with sharing class SentimentAnalysis {
    @AuraEnabled
    public static String findSentiment(String msg){
        try{
            JSONGenerator gen = JSON.createGenerator(true);    
            gen.writeStartObject();      
            gen.writeStringField('message', msg);
            gen.writeEndObject();    
	        String jsonRequestBody = gen.getAsString();
            
            HTTP h = new HTTP();
            HTTPRequest req = new HTTPRequest();
            req.setEndPoint('https://salesforcelwc.onrender.com/sentiment');
            req.setMethod('POST');
            req.setHeader('Content-Type','application/json');
            req.setBody(jsonRequestBody);
            req.setTimeout(120000);
            HTTPResponse res = h.send(req);
            String responseBody = res.getBody(); 
            
            SentimentWrapper wrap = (SentimentWrapper)JSON.deserialize(responseBody, SentimentWrapper.class);
            return wrap.intensifier;
        }catch(Exception ex){
            return 'Error while processing request';
        }
    }
    public class SentimentWrapper{
        String intensifier; 
    }
}

This Apex class makes a REST API callout to an external sentiment analysis service. It sends a JSON-formatted message to the https://salesforcelwc.onrender.com/sentiment endpoint via a POST request.

The service analyzes the message and returns a sentiment “intensifier,” which the class extracts from the JSON response using a wrapper class. This method is marked @AuraEnabled, so it can be called from Lightning components.

  1. After this, create a Lightning web component and enter the code below into the JS file.
import { LightningElement } from 'lwc';
import findSentiment from '@salesforce/apex/SentimentAnalysis.findSentiment';
export default class SentimentAnalysis extends LightningElement {
    isSpinner = false;
    strFeedback;
    strSentiment;
    error;
    handleOnchange(event){
        this[event.target.name] = event.target.value;
    }
    fetchSentiment(event){
        if(this.strFeedback){
            this.isSpinner = true;
            this.strSentiment = undefined;
            findSentiment({ msg : this.strFeedback})
                .then(result => {
                    this.strSentiment = result;
                    this.error = undefined;
                    this.isSpinner = false;
                })
                .catch(error => {
                    this.error = JSON.stringify(error);
                    this.strSentiment = undefined;
                    this.isSpinner = false;
                });
        }else{
            this.error = 'Please provide value in experience field';
            this.strSentiment = undefined;    
        }
    }
}

In the above code, we have defined the logic to take user feedback and send it to the Apex method. It uses strFeedback to store input, and when the fetchSentiment method is triggered with the button, it checks if feedback is provided.

Then it calls the Apex method with the input, and then updates strSentiment with the response or sets an error if the call fails.

  1. After this, enter the code below in the HTML file to define the UI of the Lightning web component.

In this HTML code, we have added a button to call the Apex method

<template>
    <lightning-card title="Please Share Your Experience">
        <template if:true={isSpinner}>
            <lightning-spinner alternative-text="Loading" size="small"></lightning-spinner>
        </template>
        <div class="mainContainer">
            <div class="row">
                <h1 style="font-weight:bold;">Please Share Your Experience</h1>
                <lightning-textarea 
                    name="strFeedback" 
                    value={strFeedback} 
                    onchange={handleOnchange}>   
                </lightning-textarea>
            </div>
            <br/>
            <div class="row">
                <button class="slds-button slds-button_brand slds-button_stretch"
                onclick={fetchSentiment}>Check Sentiment</button>
            </div>
            <br/>
            <template if:true={error}>
                <div class="row" style="text-align:center;">
                    <h1 class="slds-text-heading_small"><b>Error :</b> {error}</h1>
                </div>
            </template>
            <template if:true={strSentiment}>
                <div class="row" style="text-align:center;">
                    <h1 class="slds-text-heading_small"><b>Intensifier :</b> {strSentiment}</h1>
                </div>
            </template>
        </div>  
    </lightning-card>
</template>
  1. Now, to make the component visible to the Lightning pages, enter the code below in the meta.xml file.
 <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
  1. Deploy the Lightning web component to the Lightning page. In the UI, there will be an input field where you have to enter text with some expression.

In the UI, give input such as “ I was unable to complete the project on time” and click the button Check Sentiment. The output will return as “Negative“.

The API will get the request from the Apex, and it will analyze the sentiment of the text and answer accordingly in the output field Intensifier.

How to make REST api call using Apex in LWC

This way, we can make REST API calls in Salesforce Lightning web component using the Apex controller class.

Conclusion

In this Salesforce tutorial, we have learned two different approaches for making REST API callouts in Salesforce using Lightning Web Components: one with the client-side Fetch API and another with a server-side Apex controller.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.