Suppose we have a simple 3rd party REST API, and we do not want to create a bunch of APEX Classes to serve just a simple call. We can use Javascript Fetch method (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
- We need to add the URL to CSP Trusted Sites.
To able to make a callout from LWC, the first thing we need to do is to add the Endpoint in CSP trusted site, because LWC uses Content Security Polity to impose restrictions on content (https://help.salesforce.com/articleView?id=csp_trusted_sites.htm&type=5). To do this, navigate to Setup->Security-> CSP Trusted Sites.

- Let’s create an example to query lastPrice of BTC/USDT from Binance:
<!--binanceTicket.html-->
<template>
<lightning-card variant="narrow">
<h1 slot="title">{bTicket}</h1>
<h2>Current Price: {currentPrice}</h2>
<p>Previous Price: {prevPrice}</p>
<p>Change: {priChange}</p>
</lightning-card>
</template>
//binanceTicket.js
import { LightningElement,api, track } from 'lwc';
let BINANCE_URL = 'https://www.binance.com/api/v1/'
export default class BinanceTicket extends LightningElement {
@api bTicket='BTCUSDT'; // ticket BTCUSDT forexemple
@track currentPrice = 0;
@track prevPrice = 0;
@track priChange = 0;
intervalIns;
getCurrentPrice(){
let method = 'ticker/24hr';
let params = {"symbol":this.bTicket};
let burl = BINANCE_URL+method+this.convertObject2Params(params);
console.log(burl);
fetch(burl,{
method:"GET",
headers:{
"Accept":"application/json"
}
}).then(response => {
if(response.ok){
return response.json();
}
}).then(resJson => {
this.prevPrice = this.currentPrice;
this.currentPrice = Number(resJson.lastPrice).toFixed(2);
this.priChange = (this.currentPrice - this.prevPrice).toFixed(2);
})
}
convertObject2Params(obj){
return ('?' +
Object.keys(obj)
.filter(key => !! obj[key])
.map(key => `${key}=${encodeURIComponent(obj[key])}`)
.join('&')
);
}
connectedCallback(){
this.intervalIns = setInterval(()=>{
this.getCurrentPrice();
},1000);
}
}
Result:
