Hey folks! In this blog post, I will cover how we can make REST API callouts from Lightning Web Components.

What are Lightning Web Components (LWC)?

Lightning Web Components are a new UI framework introduced by Salesforce to build lightning components. Lightning Web Components use core web components standards, meaning we can make small, lightweight, and reusable web components using HTML, CSS, and modern Javascript. LWC browsers support Edge, Chrome, Firefox, and Safari. Before LWC, We use Aura components to create web components in the Salesforce platform.

Advantages of Lightning Web Components over Aura components:

  • Supports latest web component standards
  • The end-user will not see any difference between the Aura component and LWC
  • Fast, secure, and better performance
  • Ease development using (VSC)

Lightning Web Component Structure:

Similar to the Aura component bundle, a Lightning web component has multiple files (component bundle). All files should be the same with different file extensions. An LWC bundle has the following files:

  • HTML (.html file has the HTML design of component. It has a root <template> tag.)
  • JS (.js files used as a controller in MVC framework)
  • XML (.xml file used to store the configuration for the LWC, such as version, visibility and attributes )
  • .css (.css files are used to store the styling for the component)

Making Rest API Callout

In the Salesforce platform, we only use Apex to make calls to external systems for integration. Apex is a powerful server-side language. Apex provides support to HTTP and SOAP callouts. Before making callouts using apex, the external site must be added to the remote site setting or configure the named credential for the external system. We can Apex to callout from a Visualforce page, Aura component, or Batch class.

Simple Apex callout code

public class HttpCalloutSample {

  // Pass in the endpoint to be used using the string url
  public String getCalloutResponseContents(String url) {

    // Instantiate a new http object
    Http h = new Http();

     // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('GET');

    // Send the request, and return a response
    HttpResponse res = h.send(req);
    return res.getBody();
  }
}

Making a callout from LWC

As we already know, we can leverage Apex to make callouts to external services. Apex is a server-side language which means it will take more time to process than on the client-side. There are many cases where we don’t need to perform any server actions (Apex action) after calling an external API. For example, if we need to build a Lightning Web Component (LWC) to display transactions aggregated from different sources based on the record type, we don’t need any server-side processing.

For those cases, we need the ability to make callouts from lightning components. Since LWC supports modern JS, it also supports Fetch API. Fetch API provides an interface for fetching resources and is an easy, fast way to integrate with remote systems. So we can use Apex or Fetch API for integration on LWC.

When should we use the Fetch API for integration?

  • Remote Process Invocation—Fire and Forget: When we start a process on a remote server and we don’t need to wait for the completion of the process.
  • Fetch Data – when we just need to fetch data from a remote server.

A basic fetch request is really simple to set up. Have a look at the following code:

fetch('https://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

Before using Fetch API in the LWC, we need to set up the CSP Trusted Site definition for remote sites. Before making a callout from Apex we need to set up remote site settings, and in LWC we need to set up CSP trusted sites.

CSP trusted sites

CSP stands for Content Security Policies. CSP is a way to implement the W3C standard to the page. It prevents access to the page content from being accessed via a remote server. It prevents code injection attacks and cross-site scripting. To allow Fetch API to make a callout to a remote server we need to add the endpoint as CSP trusted sites.

image.pngNow we are ready to use the Fetch API in an LWC component.

For this example, we will be using the ipify API, a simple Public IP Address API. It will return the IP address of our server.

getMyIp Lightning web component:

getMyIp.html

<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="utility:connected_apps" size="small"></lightning-icon>
           My IP
        </h3>
        <div slot="footer">

        </div>
        <div class="slds-p-around_medium lgc-bg">
            <lightning-button label="Get My IP" onclick={getIP}></lightning-button>
        </div>

        <div class="slds-p-around_medium lgc-bg">
            <lightning-textarea readonly value={myIp} rows="7" style="height:150px;"></lightning-textarea>
        </div>   
    </lightning-card>
</template>

getMyIp.js

import { LightningElement, track } from 'lwc';

export default class GetMyIp extends LightningElement {
    @track myIp;

    getIP() {
       const calloutURI = 'https://api.ipify.org?format=json';
        fetch(calloutURI, {
            method: "GET"
        }).then((response) => response.json())
            .then(repos => {
                console.log(repos)
                this.myIp = repos.ip;
                console.log(this.myIp);
            });
    }
}

getMyIp.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="https://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output:

image.png
Still need Salesforce help? Just reach out, we’re happy to help.

Akhil Mandia

Akhil Mandia

Salesforce Developer

Akhil, one of our sophisticated developers, holds a deep passion for coding and software development. He has a background in website development and has continued to grow his passion in the Salesforce Ohana as a Salesforce Developer.

About Roycon
We’re an Austin-based Salesforce Consulting Partner, with a passion and belief that the Salesforce platform’s capabilities can help businesses run more efficiently and effectively. Whether you are just getting started with Salesforce or looking to realize its full potential, Roycon specializes in Salesforce Implementations, Salesforce Ongoing Support, and Salesforce Integrations, and Development. We’re the certified partner to guide the way to increase Salesforce Adoption, make strategic decisions, and build your Salesforce Roadmap for success.

Tweet
Share