LWC + API call

for beginners…

Hi, if you’re someone who’s started learning lwc recently, then this tutorial is for you.

Today, we’re going to make a simple LWC widget to convert currency using api.

Pre-requisite:

A free account in apilayer to use their api and generate api key

We are going to use API fixer api : which you can find here

Once you have signed up and created a free account, now we are ready to go:

Another important note: Add the API URL in your remote site settings

LWC code:

html

javascript

css

Apex class:

public class CurrencyConverterController {

@AuraEnabled(cacheable=true)

public static double convert(string sourceCurrency, string targetCurrency, string amount) {

HttpRequest req = new HttpRequest();

HttpResponse res = new HttpResponse();

Http http = new Http();

string today = String.valueOf(System.today());

req.setEndpoint(‘https://api.apilayer.com/fixer/convert?from='+sourceCurrency+'&to='+targetCurrency+'&amount='+amount+'&date='+today);

req.setMethod(‘GET’);

req.setHeader(‘apikey’, ‘add your api key here ’); // from api layer

res = http.send(req);

Map<string, object> responseMap = new Map<String,Object>();

if(res.getStatusCode()==200){

responseMap= (Map<string, object>) JSON.deserializeUntyped(res.getbody());

}

return (double) responseMap.get(‘result’);

}

}

Demo

Thanks for reading :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store