Perform REST API call from LWC
In this topic, we will get to know about how to perform REST callout in LWC.
To call external API from lightning web component (LWC) there are 2 ways.
- Invoking callout using Apex
- Use of fetch API
In this topic, I have discussed how to make REST API callout using Apex method.
External API that I am try to hit is numverify API which will going to validate our phone number and get relevant information.
Lets begin……
Before making callout to external resource, first thing to do is to register external url into salesforce org
To register URL first we have to create Named Credentials or Remote Site Setting and register external url on it. See image below
After register url, next step is to create apex class which will make callout to external resource.
In apex class there are 3 methods that used to perform callout
- Http — Use this class to initiate an HTTP request and response.
- HttpRequestClass — Use this class to programmatically create HTTP requests like GET, POST, PATCH, PUT, and DELETE.
- HttpResponseClass — Use this class to handle the HTTP response returned by HTTP.
Syntax
public class HttpCalloutSample {
// Pass in the endpoint to be used using the string url
public String getCalloutResponseContents(String url) {
// Instantiate a new Http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
return res.getBody();
}
}
This program runs synchronously, meaning no further processing happens until the external web service returns a response. Alternatively, you can use the @future annotation to make the callout run asynchronously.
Few useful JSON class methods
- deserialize(jsonString,apexType) — Deserializes the specified JSON string into an Apex object of the specified type. see here.
- deserializeUntyped(jsonString) — Deserializes the specified JSON string into collections of primitive data types. see here.
Demonstration Code
REST Apex class
/** Sachin Jha **/
public with sharing class RESTNumverify {
@AuraEnabled(cacheable=true)
public static List<String> doVerifyNumber(String phoneNumber, String countryCode){
list<String> lstOfData = new list<String>();
Http http = new Http();
HttpRequest request = new HttpRequest();
String accessKey = '8bf3715e1d3a2879aa2a7429ec3c52c9';
String NumverifyAPIRequest = '/api/validate?access_key='+
accessKey+'&number='+
phoneNumber+'&country_code='+
countryCode+'&format=1';
request.setEndpoint('callout:Numverify'+NumverifyAPIRequest);
request.setMethod('GET');
HttpResponse response = http.send(request);
if(response.getStatusCode() == 200){
// deserializeUntyped used to Deserializes the specified JSON string into collections of primitive data types.
MAP<String,Object> recievedData = (MAP<String,Object>)JSON.deserializeUntyped(response.getBody());
lstOfData.add('Mobile:- '+(String)recievedData.get('number'));
lstOfData.add('Country Name:- '+(String)recievedData.get('country_name'));
lstOfData.add('Carrier:- '+(String)recievedData.get('carrier'));
lstOfData.add('Location:- '+(String)recievedData.get('location'));
}
return lstOfData;
}
}
HTML File
<!-- Sachin Jha -->
<template>
<lightning-card icon-name="standard:contact" variant="base">
<div slot="title">
Number Verify API call
</div>
<div slot="footer">
<template if:true={recievedData} for:each={recievedData} for:item="data" for:index="index">
<div class="slds-m-horizontal_x-small" key={data}>
{data}
</div>
</template>
</div>
<div class="slds-m-horizontal_x-small">
<div class="slds-m-horizontal_x-small">
<lightning-input
type="text"
label="Phone Number"
name="phone"
placeholder="Enter Phone Number"
onchange={handleChange}
required="true"
style="width: 200px;"
></lightning-input>
</div>
<div class="slds-m-horizontal_x-small">
<lightning-input
type="text"
label="Country Code"
name="country"
placeholder="eg. IN, AUS, US"
onchange={handleChange}
required="true"
style="width: 200px;"
></lightning-input>
</div>
<br>
<lightning-button variant="brand"
label="Verify"
title="Verify Number"
onclick={clickHandler}
class="slds-m-left_x-small">
</lightning-button>
</div>
</lightning-card>
</template>
JS File
// Sachin Jha
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import RestAPICall from '@salesforce/apex/RESTNumverify.doVerifyNumber';
export default class LwcVerifyNumber extends LightningElement {
contactNumber;countryCode;
recievedData;
handleChange(event){
let {name,value} = event.target;
console.log('Name:- '+name+' Value:- '+value)
if(name == 'phone'){
this.contactNumber = value;
}if(name == 'country'){
this.countryCode = value;
}
}
async clickHandler(){
this.recievedData = await this.makeAPICall()
console.log('Data:- '+this.recievedData);
if(this.recievedData.length){
this.dispatchEvent(new ShowToastEvent({
title: "Verification",
message: "your contact number verification is done",
variant: "success"
}));
}
}
makeAPICall(){
return RestAPICall({phoneNumber:this.contactNumber,
countryCode:this.countryCode})
.then((result)=>{
return result;
})
.catch((error)=>{
console.log(error);
})
}
}
Follow me on linkedIn and Twitter for such more related post
Comments
Post a Comment