Sunday, September 4, 2022

Rest API Callout from LWC (Lightning Web Component)



Hello, everyone! In this blog post👇, I'll show you how to call REST APIs from Lightning Web Components.

What is REST API

An application programming interface (API or web API) that complies with the requirements of the REST architectural style and permits interaction with RESTful web services is referred to as a REST API (also known as a RESTful API). REST stands for  Representational State Transfer.

REST is an architectural set of restrictions rather than a protocol or standard. REST can be implemented by API developers in a variety of ways.

A RESTful API transmits a representation of the resource's state to the requester or endpoint when a client request is made through it. One of various formats, including JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text, is used to deliver this information or representation via HTTP. Despite its name, JSON is the most widely used file format because it can be read by both humans and machines and is language-independent.


Salesforce Lightning Web Components are a UI framework for creating lightning components. Lightning Web Components adhere to core web component standards, allowing us to create small, lightweight, and reusable web components with HTML, CSS, and modern JavaScript.

An LWC bundle contains the following files:
  1. HTML (.html file contains the HTML design of the component. It has a root <template> tag.)
  2. JS (.js files used as a controller in MVC framework)
  3. XML (.xml file used to store LWC configuration such as version, visibility, and attributes)
  4. css (.css files are used to store the styling for the component)
In this blog we are going to utilise the currency convert api that is provided by getgeoapi. To utilise this service we will required an api Key.

To get your free api key:

After signing up and validating your email, you will be able to find your API Key in your dashboard. 

After getting the api key you can test this api using Postman and other api testing tools.

Example To make a request:

GET: https://api.getgeoapi.com/v2/currency/convert
?api_key={YOUR_API_KEY}
&from=EUR
&to=GBP
&amount=10
&format=json
After requesting you will get an json Response like this :

{
    "status":"success",
    "updated_date":"2018-12-27",
    "base_currency_code":"EUR",
    "amount":10,"
    "base_currency_name":"Euro",
    rates":{
        "GBP":{
            "currency_name":"Pound Sterling",
            "rate":"0.9007",
            "rate_for_amount":"9.0070"
        }
    }
}



In this we are going to create a lightning web component in which we were provide an option to the user to select from which to which currency he/she want to convert. For this we will provide a picklist to the user TO Select the currency like given below: 
once User clicks on convert button. User will able to see the following details:  


To do callouts from lightning web components we'll use the Fetch API. Because LWC supports modern JS, it also supports the Fetch API. Fetch API provides an interface for retrieving resources and is a simple and quick way to integrate with remote systems.

The basic syntax for fetch API is shown below:

fetch('<reuestURL>',
      {
          method:"<Method Name>", // Like GET,POST
          headers:
          {
               "Content-Type": <Content Type> // Like application/Json
               "Authorization":"OAuth <EnterYourAccessToken>"
          }
         

      })
      .then(response=>response.json())
      .then(response=>{

         
      })
      .catch((error)=>{
          console.log(error);
      })



Make sure your endpoint is white-list in Content Security Policies(CSP)

Path:
From Setup, enter CSP Trusted Sites in the Quick Find box, and then CSP Trusted Sites

Enter the endpoint URL https://api.getgeoapi.com and save.


We are now ready to create the lightning web component after you have whitelisted the endpoint URL.

currencyConversionLwc.html

<template>
<lightning-card title="Currency Convertor">
<div class="slds-form slds-p-around_medium">

<div class="slds-form__row">
<div class="slds-form__item" role="listitem">
<div class="slds-form-element slds-form-element_horizontal ">
<lightning-combobox label="From Currency" options={fromCurrencyoptions}
value={fromCurrencyValue} onchange={handleFromCurrencyValueChnage} >
</lightning-combobox>
</div>
</div>
<div class="slds-form__item" role="listitem">
<div class="slds-form-element slds-form-element_horizontal ">
<lightning-combobox label="To Currency" options={toCurrencyoptions}
value={toCurrencyValue} onchange={handleToCurrencyValueChnage} >
</lightning-combobox>
</div>
</div>

<div class="slds-form__item" role="listitem">
<div class="slds-form-element slds-form-element_horizontal ">
<lightning-button label="Convert" title="Convert"
onclick={handleConversion}></lightning-button>
</div>
</div>

</div>

</div>

<div class=" slds-p-around_medium">
<template if:true={finalResult}>
<div class=" slds-p-around_medium" style="background-color:orange ;">

<p class="slds-align_absolute-center" style="font-size:18px">
Exchange Rate Information from {fromCurrencyValue} to {toCurrencyValue}
</p>
<div>
<dl class="slds-dl_inline">

<dt class="slds-dl_inline__label">From Curreny Name: </dt>
<dd class="slds-dl_inline__detail">{finalResult.from_currency_name}</dd>

<dt class="slds-dl_inline__label">From Currency Code: </dt>
<dd class="slds-dl_inline__detail">{finalResult.from_currency_code}</dd>

<dt class="slds-dl_inline__label">To Curreny Name: </dt>
<dd class="slds-dl_inline__detail">{finalResult.to_currency_name}</dd>

<dt class="slds-dl_inline__label">To Currency Code: </dt>
<dd class="slds-dl_inline__detail">{finalResult.to_currency_code}</dd>

<dt class="slds-dl_inline__label"> Exchange Rate: </dt>
<dd class="slds-dl_inline__detail">{finalResult.exchange_rate}</dd>

</dl>

</div>
</div>

</template>
</div>

</lightning-card>
</template>




currencyConversionLwc.js

In JS we are going to use apiKey and accessToken. So we have the apiKey as we discussed how to get in the earlier steps. Now next thing is to get Acees Token.

Here are the steps to get Access Token:

1. Go to setup and Search for App Manger and at the top right you will able to see the button New Connected App. Click on it



Click Save Button. After this you will able to see this message Changes can take up to 10 minutes to take effect. Deleting a parent org also deletes all connected apps with OAuth settings enabled  and then hit continue button. After some time you will get Client Id and client secret.

Next step is to go to the Postman and create a post request with this url https://login.salesforce.com/services/oauth2/token?grant_type=password and in params pass the parameters like below. 

grant_type: password
client_id: A300F2BB7862D38A7384825CE1C8E6A78267CB3FA2CC0919AFC667292CE23455
client_secret: A300F2BB7862D38A7384825CE1C8E6A78267CB3FA2CC0919AFC667292CE23455
username: omsfdc@tutorial.com (Your Salesforce UserName)
password: @1234pqxcoX8m6FLWzc (Your SalesforcePassword+SecurityToken)

if my salesforce Paassword is : @123
and Security Token is :4pqxcoX8m6FLWzc
Then password will be : @1234pqxcoX8m6FLWzc


To get Security token in salesforce
1. Log in to your Salesforce account
2. Click the profile avatar and choose Settings
3. Select My Personal Information → Reset My Security Token
4. Check your email for the security token


After this click send button and after clicking you will get your access token.

{
    "access_token""00D5i000005mP1y!AR8AQMY9OoKMUUwD4QfuQU_BFA6seI",
    "instance_url""https://globant-10d-dev-ed.my.salesforce.com",
    "id""https://login.salesforce.com/id/00D5i000005mP1yEAE/0055i000003Z4bpAAC",
    "token_type""Bearer",
    "issued_at""1662190068945",
    "signature""n26Gdh6oeQnVgsq8C2ehDKqzQ3Sfm4ptOIftqe4+AYE="
}

Now let's do our js part

import { LightningElement,track } from 'lwc';
const options=[
{label:"INR",value:"INR"},
{label:"EUR",value:"EUR"},
{label:"USD",value:"USD"},
{label:"CAD",value:"CAD"},
{label:"GBP",value:"GBP"}
];

export default class CurrencyConversionLwc extends LightningElement {

@track fromCurrencyoptions =options;
@track toCurrencyoptions =options;
fromCurrencyValue;
toCurrencyValue;

@track finalResult;


handleFromCurrencyValueChnage(event){
this.fromCurrencyValue=event.target.value;
}

handleToCurrencyValueChnage(event){
this.toCurrencyValue=event.target.value;
}


handleConversion(event){
fetch('https://api.getgeoapi.com/v2/currency/convert?
api_key=12345
&from='+this.fromCurrencyValue+'&to='+this.toCurrencyValue+'&amount=1&format=json',
{
method:"GET",
headers:{

"Authorization":"OAuth ffnkfnefheof4242y23878kllknlnlknd"
}

})
.then(response=>response.json())
.then(response=>{

let objData={
from_currency_name:'',
from_currency_code:'',
to_currency_name:'',
to_currency_code:'',
exchange_rate:'',
last_refreshed:''

};
let exchangeData=response;
objData.from_currency_name=exchangeData["base_currency_name"];
objData.from_currency_code=exchangeData["base_currency_code"];
objData.last_refreshed=exchangeData["updated_date"];
let convertdata=response["rates"];
let innerdata=convertdata[this.toCurrencyValue];
objData.to_currency_name=innerdata["currency_name"];
objData.exchange_rate=innerdata["rate_for_amount"];
objData.to_currency_code=this.toCurrencyValue;
this.finalResult=objData;
})
.catch((error)=>{
console.log(error);
})

}
}


currencyConversionLwc.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<masterLabel>Currency Conversion LWC</masterLabel>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightningCommunity__Default</target>
<target>lightningCommunity__Page</target>
</targets>
</LightningComponentBundle>


Output:-
                       

We hope that you find this blog helpful, if you still have queries, don’t hesitate to contact us at omsfdc91@gmail.com.

No comments:

Post a Comment