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