Callout from LWC (Lightning Web Component)

In this post, we will implement the functionality to make an external callout from LWC (Lightning Web Component). We will make the use of Named Credentials as well. So let’s get into the implementation.

Implementation

To implement a callout from LWC, we will create a button on Lightning Web Component that will call the Apex method. From an Apex method, we will make an API call that will return a cute picture of Dog.

Callout from LWC
Callout from LWC

Create Named Credential

First, create a Named Credentials Dog_API with callout endpoint. We are using below endpoint for this implementation:

https://dog.ceo/api/breeds/image/random

Select Anonymous as Identity Type and No Authentication as Authentication Protocol. Check this Named Credential implementation post to see how it works in detail. This is how your Named Credential should look like:

Named Credentials in Salesforce
Named Credentials in Salesforce

Then, create an Apex class with fetchRandomDog method that will use above Named Credential to make an API call and get the URL for the image.

DogAPIController.apxc

public with sharing class DogAPIController {

    @AuraEnabled
    public static String fetchRandomDog() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
         
        // Provide the Named Credentials
        request.setEndpoint('callout:Dog_API');
        request.setMethod('GET');        
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            return response.getBody();
        }
        return null;
    }
}

Callout from LWC

Now, create a Lightning Web Component with a button and add img tag to display image. Add lightning-spinner to show the spinner while loading. Display image in the if condition so that it will be displayed only if we get a response from API using boolShowImage property. After clicking a button, the handleClick method will be called.

calloutDog.html

<template>
    <lightning-card title="Callout from Lightning Web Component">
        <lightning-layout>
            <div class="slds-p-around_small">
                <lightning-button variant="brand" 
                    label="Get Cute Dog Picture"
                    onclick={handleClick}>
                </lightning-button>
                <br/><br/>

                <template if:true={boolShowImage}>
                    <img src={strUrl} width="400" height="400"/>
                </template>

                <template if:true={boolShowSpinner}>
                    <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
                </template>

            </div>
        </lightning-layout>
    </lightning-card>
</template>

In JS Controller, handleClick method will hide the image, show the spinner, and will make an imperative call to the Apex method. It will return a response with message property which contains the URL of the image. Assign it to the strUrl which is the src for our image. Check this implementation to know how to call the Apex method from LWC in detail which also includes multiple ways to call Apex from LWC.

calloutDog.js

import { LightningElement } from 'lwc';
import fetchDog from '@salesforce/apex/DogAPIController.fetchRandomDog';

export default class CalloutDog extends LightningElement {

    boolShowImage = false;
    boolShowSpinner = false;
    strUrl;

    handleClick(){
        this.boolShowSpinner = true;
        this.boolShowImage = false;
        fetchDog({}).then(response => {
            this.strUrl = JSON.parse(response).message;
            this.boolShowImage = true;
            this.boolShowSpinner = false;
        }).catch(error => {
            console.log('Error: ' +error.body.message);
        });
    }
}

This is how we can implement an external Callout from LWC (Lightning Web Component). If you don’t want to miss new posts, please Subscribe here.

If you want to check more implementation using Lightning Web Components, you can check it here.

Check official Salesforce documentation about API Callouts here.

See you in the next implementation!

2 thoughts on “Callout from LWC (Lightning Web Component)”

  1. Great article, very informative.

    Wondering if its possible to recreate this article but utilizing the fetch() function in your JS file rather than queueing APEX?

    I have a use case that requires a request to a 3rd party passing API_key && API_secret and includes a phone number to tell the system what data is being queried.

    Is it possible to recreate this using a 3rd party that requires more authorization and parameters to access info?

    Thank you!

    Love the articles

Leave a Reply

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