
When working with Lightning Web Components (LWC), making REST API callouts is a common requirement to interact with external data sources. One of the most efficient ways to achieve this is using the Fetch API. The Fetch API is a modern and versatile JavaScript interface designed to make HTTP requests directly from web browsers. Unlike the older XMLHttpRequest, the Fetch API offers a cleaner, more intuitive syntax, making it easier to work with. It provides a more flexible and powerful way to handle network requests, bringing a more streamlined and contemporary approach to interacting with server data in JavaScript. This makes it a go-to choice for developers building responsive, data-driven web applications.
Why use Fetch API?
The Fetch API offers several advantages over older methods like XMLHttpRequest:
Cleaner Syntax: The Fetch API uses promises, which provide a more readable and manageable way of handling asynchronous operations.
Flexibility: It allows you to customize request options such as headers, request methods (GET, POST, PUT, DELETE), and body data (e.g., JSON, FormData).
Enhanced Capabilities: The Fetch API can handle more complex scenarios, like streaming responses, better than traditional methods.
Step-by-Step: Making a REST API Callout Using Fetch API in LWC
Step 1- Create a remote site setup in the Salesforce org.
Go to Setup => Type remote Site

Step 2- Add a CSP(Trusted URLs) site in the Salesforce org..
Go to Setup => CSP or Trusted URLs

If you do not create the trusted URLs then you will get an error as below

Let’s see an example!
Implement a dynamic instantiation feature for Lightning Web Components (LWC) in Salesforce, allowing components to be loaded and rendered based on user interaction or specific runtime conditions. This feature should optimize performance by only loading necessary components, enhance flexibility by adapting the UI dynamically, and reduce bundle size by avoiding unnecessary imports.
The images below display the result we will achieve at the end of the blog.


Step 3- Create an LWC Component
Start by creating an LWC component named dogImageUsingFetchApi:
sfdx force:lightning:component:create --type lwc --componentname dogImageUsingFetchApi
This will generate the basic files you need (dogImageUsingFetchApi.html, dogImageUsingFetchApi.js, and dogImageUsingFetchApi.css).
Step 4- Set Up the Component HTML
In dogImageUsingFetchApi.html, set up a simple user interface that will display the Dog Image:
<template>
<lightning-card title={labels.DOG_IMAGE_GENERATOR_TITLE} icon-name="custom:custom63">
<lightning-layout class="dog-layout">
<lightning-button
label={labels.DOG_IMAGE_GENERATOR_BUTTON_LABEL}
onclick={handleClick}
class="generate-button">
</lightning-button>
<div class="slds-p-around_small">
<template if:true={loadingSpinner}>
<lightning-spinner alternative-text="Loading" variant="brand" size="large"></lightning-spinner>
</template>
<template if:true={imageReady}>
<div class="dog-image-container">
<img src={pictureUrl} alt="Random Dog" class="dog-image"/>
</div>
</template>
</div>
</lightning-layout>
</lightning-card>
</template>
This template includes:
A button that triggers the handleClick method.
An area to display error messages as a Show Toast message.
Step 5- Write the JavaScript Logic
In dogImageUsingFetchApi.js, implement the logic to fetch data from an external API using the Fetch API:
/************************************************************************
(c) Copyright 2024 Avenoir Technologies Pvt. Ltd. All rights reserved.*
Created by: Manish Kumar Gupta
Ticket Number: AVEBLOG-109
------------------------------------------------------------------------*
Blog: Making REST Api callout using LWC component
------------------------------------------------------------------------*
Version History:*
VERSION DEVELOPER NAME DATE DETAIL FEATURES
1.0 Manish Kumar Gupta 02/10/2024 Initial Development
***********************************************************************/
import {LightningElement} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import DOG_IMAGE_GENERATOR_TITLE from '@salesforce/label/c.DOG_IMAGE_GENERATOR_TITLE';
import DOG_IMAGE_GENERATOR_BUTTON_LABEL from '@salesforce/label/c.DOG_IMAGE_GENERATOR_BUTTON_LABEL';
import DOG_API_URL from '@salesforce/label/c.DOG_API_URL';
import ERROR_MESSAGE_FOR_TYPE_ERROR from '@salesforce/label/c.ERROR_MESSAGE_FOR_TYPE_ERROR';
import ERROR_MESSAGE_FOR_HTTP_ERROR from '@salesforce/label/c.ERROR_MESSAGE_FOR_HTTP_ERROR';
import ERROR_MESSAGE_FOR_UNEXPECTED_ERROR from '@salesforce/label/c.ERROR_MESSAGE_FOR_UNEXPECTED_ERROR';
import HTTP_LABEL from '@salesforce/label/c.HTTP_LABEL';
import ERROR_MESSAGE_TITLE_FETCH_API from '@salesforce/label/c.ERROR_MESSAGE_TITLE_FETCH_API';
export default class DogImagesUsingFetchApi extends LightningElement {
imageReady = false;
pictureUrl = '';
loadingSpinner = false;
labels = {
DOG_IMAGE_GENERATOR_TITLE,
DOG_IMAGE_GENERATOR_BUTTON_LABEL,
ERROR_MESSAGE_FOR_TYPE_ERROR,
HTTP_LABEL,
DOG_API_URL,
ERROR_MESSAGE_FOR_HTTP_ERROR,
ERROR_MESSAGE_FOR_UNEXPECTED_ERROR,
ERROR_MESSAGE_TITLE_FETCH_API
}
handleClick() {
this.imageReady = false;
this.loadingSpinner = true;
fetch(this.labels.DOG_API_URL, {method: 'GET'})
.then(response => response.json())
.then(data => {
this.pictureUrl = data.message;
this.imageReady = true;
this.loadingSpinner = false;
})
.catch(error => {
const event = new ShowToastEvent({
title: this.labels.ERROR_MESSAGE_TITLE_FETCH_API,
message: this.getErrorMessage(error),
variant: 'error',
});
this.dispatchEvent(event);
this.loadingSpinner = false;
});
}
getErrorMessage(error) {
let errorMessage = '';
if (error instanceof TypeError) {
errorMessage = this.labels.ERROR_MESSAGE_FOR_TYPE_ERROR;
} else if (error.message.includes(this.labels.HTTP_LABEL)) {
errorMessage = this.labels.ERROR_MESSAGE_FOR_HTTP_ERROR;
} else {
errorMessage = this.labels.ERROR_MESSAGE_FOR_UNEXPECTED_ERROR;
}
return errorMessage;
}
}
handleClick(): Fetches a dog image from the API, updates the display with the image URL and shows an error message if the fetch fails.
getErrorMessage(error): Returns a specific error message based on the type of error encountered during the fetch operation.
Step 6- Write the CSS
In dogImageUsingFetchApi.css
.dog-layout {
display: flex;
flex-direction: column;
align-items: center;
}
.generate-button {
background-color: #ffcc00;
color: #fff;
font-weight: bold;
border-radius: 0.3rem;
transition: background-color 0.3s ease;
}
.generate-button:hover {
background-color: #ff9900;
}
.dog-image-container {
margin-top: 1.2rem;
border-radius: 0.6rem;
overflow: hidden;
box-shadow: 0 0.25rem 0.93rem rgba(0, 0, 0, 0.2);
}
.dog-image {
width: 100%;
height: auto;
border-radius: 0.6rem;
}
When to use LWC with Fetch API for External Callouts:
Using If the external service does not require Salesforce authentication and can be accessed anonymously (e.g. Dog image or weather APIs).
The data fetched does not need to be processed or stored within Salesforce. It is only for immediate use in the UI, such as updating the component display in real time.
When the number of calls is low, the volume won't run into Salesforce governor limits since these calls occur outside the platform.
When to use Apex Call-out to External Servies(Apex):
There are times when making a callout through Apex is preferable, especially when:
If the external service requires secure authentication (e.g., OAuth 2.0), Apex can manage it using Named Credentials or authentication flows.
When the data needs to be processed, transformed, or stored in Salesforce objects (e.g., saving the response to a custom object).
If callouts need to be controlled to avoid performance issues or meet Salesforce API limits. Using Apex allows better control and handling.
If the external service callout needs to happen as part of a trigger, batch job, or other server-side logic.
Comparison Table: LWC Fetch API vs. Apex Callout to External API
Criteria | LWC Fetch API | Apex Callout |
Authentication | No Salesforce authentication management | Handles Named Credentials and OAuth |
Data Usage | Immediate use in UI | Data can be processed, transformed, or stored |
Governor Limits | No impact on Salesforce governor limits | Subject to Salesforce governor limits |
Error Handling | Managed on the client side (browser) | Centralized server-side error handling |
Performance Impact | Offloads processing to the client | Controlled execution within Salesforce |
When to Use | For non-critical or public data | For secure, authenticated, or critical data flows |
Conclusion
Using the Fetch API in Lightning Web Components (LWC) provides a powerful, modern way to make REST API callouts. Its clean syntax and flexibility simplify the process of handling server data, making it ideal for building responsive and interactive web applications. By following the steps above, you can easily set up your LWC component to make GET and POST requests, handle responses, and manage errors effectively. Whether you’re fetching data to display to users or sending new data to external services, the Fetch API makes integrating with RESTful services straightforward and efficient. Happy coding!
If you'd like to see the code and resources used in this project, you can access the repository on GitHub.To access the AVENOIRBLOGS repository, click here. Feel free to explore the code and use it as a project reference.
Thank You! You can leave a comment to help me understand how the blog helped you. If you need further assistance, please contact us. You can click "Reach Us" on the website and share the issue with me.
Reference
Blog Credit:
M. Gupta
Salesforce Developer
Avenoir Technologies Pvt. Ltd.
Reach us: team@avenoir.ai
Comments