LWC: Using Fetch() to make API callouts
for Salesforce developers
The Fetch API is a promise-based interface for fetching resources by making HTTP requests to servers from web browsers. It is similar to XML HTTP requests but better and more powerful.
For example, we can use a network request to:
- Submit an order,
- Load user information,
- Receive the latest updates from the server
…And all of that without reloading the page!
There’s an umbrella term “AJAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript. We don’t have to use XML though: the term comes from old times, and that’s why that word is there. You may have heard that term already.
The basic fetch request can be explained by the following code:
let promise = fetch(url, [options])
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
} else {
alert("HTTP-Error: " + response.status);
}
Second, to get the response body, we need to use an additional method call.
Response
provides multiple promise-based methods to access the body in various formats:
response.text()
– read the response and return it as text,response.json()
– parse the response as JSON,response.formData()
– return the response asFormData
objectresponse.blob()
– return the response as Blob (binary data with type),response.arrayBuffer()
– return the response as ArrayBuffer (low-level representation of binary data)- additionally,
response.body
is a ReadableStream object, it allows you to read the body chunk-by-chunk, we’ll see an example later.
Understanding it from the Lens of LWC
Let us consider a small project where we want to create a LWC component that uses fetch() to bring data by making an API callout.
For this, let’s build a Temperature display widget
import { LightningElement } from "lwc";
/*SUBSCRIBE HERE FOR FREE API KEY: https://home.openweathermap.org/users/sign_up*/
export default class WeatherWidget extends LightningElement {
currentTemperature;
city;
makeCallout(){
const apiKey = 'YOUR_API_KEY';
const units = 'metric'; // Use 'metric' for Celsius
const endpoint = `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&units=${units}&appid=${apiKey}`;
try{
fetch(endpoint)
.then(response => response.json())
.then(data => {
console.log('@@@ data'+JSON.stringify(data));
if(data){
this.currentTemperature = data.main?.temp;
}else{
console.log("data not returned");
}
console.log(' this.currentTemperature '+ this.currentTemperature);
});
} catch(error){
console.log("error occured due to"+JSON.stringify(error));
}
}
searchKeyword(event){
this.city= event.target?.value;
console.log('city name typed ... '+this.city);
if(this.city){
this.makeCallout();
}
}
}
In the above code, you can see fetch() is used to make a callout and get the Temperature from the JSON body returned.
Note:
- Make sure you have added the url in remote site settings
- Make sure you have created CSP trusted site for the website/url
The working of the LWC :
Full code : https://app.lwc.studio/edit/qk5cAPAPfMXFReeb9UO6/src/?p=stories
Resources :
UI/UX Design from Dribble https://dribbble.com/shots/9799486-Weather-App-Neumorphism-Soft-UI-Design
Disclaimer:
This is not a production ready code , best practices like making callout from Apex class is still the best approach using named credentials or likewise some other authentication mechanism .
This blog is only to demonstrates the use case of making callout using LWC only by utilising fetch() method. The Fetch API is still in active development. We can expect better features in the near future.
If you want to read how to actually use LWC along with apex to make API request , please read my other article here
Thanks for reading !