Skip to main content
  1. Salesforce.com/

3rd Party API Integration Using Lightning Web Components

·5 mins

LWCs are amazing and sometimes I think they are able to do far more things we give them credit for.

But, being the salesforce full-stack developers we are, we tend to focus a lot more on integrating salesforce data. While that makes sense most of the times, there are a few cases where we would want to the nitty-gritty of blending Salesforce data with those sometimes pesky 3rd party APIs – all through the lens of Lightning Web Components (LWC).

We’ll cover the why’s, the how’s, and even the whoa-didn’t-see-that-coming’s of Salesforce and API integration using LWC. Let’s get the ball rolling.

Why Lightning Web Components for Salesforce Integration? #

The LWC Advantage #

Before we jump into the deep end, let’s understand why LWC is the superhero in our story. LWC is Salesforce’s modern UI framework, designed to be lightweight, fast, and oh-so-efficient. It’s like the sports car of the coding world: sleek, fast, and turns heads (or in this case, turns lines of code into stunning interfaces).

Integrations in LWC #

Integrations have always been a key part of a Salesforce application. But, one seldom does not associate LWC directly with integrations.

However, all modern web front-ends have multiple things going for them.

  1. They can easily consume data and the data exchange is more standardized than ever
  2. Plugging into Salesforce data (headless, anyone) is easy and standard, but so is securely getting data from 3rd party sources
  3. There are front-end integration patterns that are a necessity rather than a luxury - think of the need to integrate with a payment gateway, a chatbot, a map solution, a video conferencing solution, or a document signing solution.. you get the point.

And with LWC, it’s easier than ever to integrate Salesforce data with 3rd party APIs. There are two main ways to do this:

1. Using Salesforce Apex with LWC for API Calls #

Apex is Salesforce’s own programming language, and it plays super nicely with LWC. Think of Apex as the translator who helps LWC understand what the 3rd party API is trying to say.

Here’s how you can make it rain data (pun intended):

@AuraEnabled(cacheable=true)
public static String getWeatherData(String location) {
    // Callout to external weather service
    // Parse and return data
}

In your LWC component:

import { LightningElement, wire } from 'lwc';
import getWeatherData from '@salesforce/apex/YourController.getWeatherData';

export default class WeatherComponent extends LightningElement {
    @wire(getWeatherData, { location: 'San Francisco' })
    weather;
}

2. Direct API Calls from LWC #

Sometimes, you gotta go direct. Especially when real-time data is the name of the game. No Apex / no Flows / no fuss. Just you, your LWC component, and the API.

Getting Started with Direct APIs #

Ensure you’ve set up your CORS and Remote Site Settings in Salesforce.

  • See how to add site to CSP Trusted Sites. CSP will infom Salesforce that an external site is trusted and can be accessed from Salesforce.
  • Ensure that that the external API can indeed be called by the salesforce (or the custom) domain in use. This is done by the 3rd party server

And, then it should be as simple as..

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

When padded with all necessary components, it looks somewhat like this ..

import { LightningElement, track } from 'lwc';

export default class WeatherComponent extends LightningElement {
    @track weatherInfo;
    @track error;

    connectedCallback() {
        this.fetchWeatherData('San Francisco');
    }

    fetchWeatherData(location) {
        // OpenWeatherMap API endpoint with API key (replace YOUR_API_KEY)
        const url = `https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=YOUR_API_KEY`;

        fetch(url)
            .then(response => {
                if (!response.ok) {
                    this.error = 'Error fetching weather';
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                this.weatherInfo = data;
            })
            .catch(error => {
                this.error = error;
                this.weatherInfo = undefined;
            });
    }
}

Do not use this code as-is except for testing purposes - note that the API key is exposed in the code.

And, the HTML template would look something like this ..

<template>
    <lightning-card title="Weather Information" icon-name="utility:forecast">
        <template if:true={weatherInfo}>
            <p class="slds-p-horizontal_small">Location: {weatherInfo.name}</p>
            <p class="slds-p-horizontal_small">Temperature: {temperature}</p>
            <!-- Add more data displays as needed -->
        </template>
        <template if:true={error}>
            <p class="slds-p-horizontal_small">{error}</p>
        </template>
    </lightning-card>
</template>

Best Practices for LWC and API Integration #

  1. Security First: Always prioritize security.
    • Implement robust authentication, such as OAuth, to secure API interaction
    • Utilize encryption for sensitive data in transit- standard TLS should be sufficient for most cases
    • Conduct security audits and penetration tests to identify vulnerabilities
  2. Monitoring: Keep an eye on your integrations.
    • Use Salesforce monitoring tools to track the health and performance of the LWC
    • Monitor the external API for uptime, response time, and rate limit usage
    • Implement detailed logging for both the Salesforce and external API interactions
  3. Error Handling: Be prepared for the unexpected. Even APIs have bad days.
    • Set up alerts for errors and failures
    • Bullet-proof design always provides for easy ways to check errors, and retry or recover from them
  4. Performance Tuning:
    • Keep your LWC components lean and mean. No one likes a slow dance at the data party
    • Implement caching to reduce API call frequency, especially for static or infrequently changing data
    • Request only the necessary data fields to reduce payload size
    • Use batch processing for handling large data volumes and do that asynchronously