Api Callout From LWC

Api Callout From LWC

Salesforce Api Callout From LWC

API callout from LWC:- Salesforce has limitations on certain features. For  API callouts, we are able to do 100 callouts in a single transaction in the Apex class. If we do more than 100 callouts, then we will get a callout limit exception. If we do callout from lightning web components(LWC), we have avoided the callout limitation while creating callout in LWC itself.

 If we need to achieve the callout from LWC, then we have to add the target API URL to a CSP trusted site.


The Lightning Component framework uses Content Security Policy (CSP) to impose restrictions on content. The main objective of CSP is to help prevent cross-site scripting (XSS) and other code injection attacks. To use third-party APIs that make requests to an external (non-Salesforce) server or to use a WebSocket connection, add the server as a CSP Trusted Site.

Create CSP Trusted Site Record

Go to Setup => CSP Trusted Sites => Create New

Note: We have to wait for some more minutes to activate this site, when the CSP trusted site was created.

Create Lightning Web Component


    <lightning-card title="random picture">
            <div class="slds-p-around_small">
                <lightning-button variant="success" 
                    label="Fetch Random Picture"
                <template if:true={ShowImg}>
                    <img src={ImageUrl} height="350" width="350"/>
                <template if:true={loadingSpinner}>
                    <lightning-spinner alternative-text="Loading" variant="inverse" 


import { LightningElement } from 'lwc';
export default class CalloutFromJS extends LightningElement {
    ShowImg = false;
    loadingSpinner = false;
	handleClick() {
		this.loadingSpinner = true;
        this.loadingSpinner = true;
            .then(response => response.json())
            .then(data => {
                let RandomIndex = Math.floor(Math.random() * 20)
                this.ImageUrl = data.hits[RandomIndex].largeImageURL;
                this.ShowImg = true;
                this.loadingSpinner = false;


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

After creating the component, we are able to do callout from JS itself. By using this method we can avoid callout limitation exception,cpu limit exceptions at all.