How to make HTTP callout from lightning component

REST callouts are based on HTTP. To understand how callouts work, it’s helpful to understand a few things about HTTP. Each callout request is associated with an HTTP method and an endpoint. The HTTP method indicates what type of action is desired.

9e44c283a52e2f5ac41ea9d332799104_apex_integration_callouts_diagram.jfif

The following are descriptions of common HTTP methods.

HTTP MethodDescription
GETRetrieve data identified by a URL.
POSTCreate a resource or post data to the server.
DELETEDelete a resource identified by a URL.
PUTCreate or replace the resource sent in the request body.

We will create a lightning component to make a HTTP callout and send a GET request to a web service to get the foreign exchange rates. We will use URL http://data.fixer.io/api/latest to get latest exchange rate.

Step1: Authorize endpoint URL
Add new remote site setting for URL http://data.fixer.io/api/

remotesite.JPG

step2: Create Apex class to make HTTP callout, Class name: exchangeRateController.apxc

public class exchangeRateController {
@AuraEnabled
public static Map < String,Object > getExchangeRate(String url) {
// Instantiate a new http object
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod('GET');

// Send the request, and return a response
HttpResponse res = h.send(req);

// Deserialize the JSON string
Map < String,Object > mapOfExchangeRate = (Map < String, Object > ) JSON.deserializeUntyped(res.getBody());
system.debug('exchange rate map: ' + mapOfExchangeRate);

return mapOfExchangeRate;
}
}

Spet 3: create lightning component
Component Name: exchangeComponent.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,forceCommunity:availableForAllPageTypes" access="global" controller="exchangeRateController">
<aura:attribute name="response" type="Map"/>
<aura:attribute name="ListOfCurrency" type="List"/>
<aura:attribute name="title" type="String" default="Foreign exchange rates using lightning component HTTP callout"/>
<aura:attribute name="showBody" type="boolean" default="false"/>
<lightning:card title="{!v.title}">
<lightning:button variant="brand" label="Get Exchange Rate" onclick="{! c.calloutCtrMethod }" />
</lightning:card>
<aura:if isTrue="{!v.showBody}">
<div class="slds-m-around--medium">
<table border="1" width="200">
<tr>
<th colspan="2">Base : {!v.response.base}</th>
</tr>
<tr>
<th colspan="2">Date : {!v.response.date}</th>
</tr>
<tr>
<th>Currency</th>
<th>Rate</th>
</tr>
<aura:iteration items="{!v.ListOfCurrency}" indexVar="key" var="rate">
<tr>
<td>{!rate.key}</td>
<td>{!rate.value}</td>
</tr>
</aura:iteration>
</table>
</div>
</aura:if>
</aura:component>

Js Controller Name: exchangeComponentController.js

({
calloutCtrMethod : function(component, event, helper) {
component.set("v.showBody", true);
// call helper method
helper.getResponse(component);
},
})

Js Helper Name: exchangeComponentHelper.js

({
getResponse: function(component) {
// create a server side action.
var action = component.get("c.getExchangeRate");
action.setParams({
"url": 'http://data.fixer.io/api/latest?access_key=YOURACCESSKEY'
});
action.setCallback(this, function(response) {
var state = response.getState();
if (component.isValid() && state === "SUCCESS") {
component.set("v.response", response.getReturnValue());

// this will retuen map, we will take Rates parameter from map
var getAllRates = component.get("v.response")['rates'];
var cols = [];

for (var key in getAllRates) {
// push Currency and exchange rate on cols Map
cols.push({
value: getAllRates[key],
key: key
});
}

component.set("v.ListOfCurrency", cols);

}
});
$A.enqueueAction(action);
}
})

You have replace access key by registering to free account at https://fixer.io/.

Step 4: Create Test App to test your application, you can also create tab for component we have created above.

<aura:application extends="force:slds">
<c:exchangeComponent/>
</aura:application>

Output:

Published by

Suhas Rathod

I'm Suhas Rathod. I am an energetic, self-confident and experienced Full Stack Programmer with a passion for working with different technology.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.