
How to Make HTTP Callout from Lightning component
Prerequisites : Basic understanding of Lightning Components.
HTTP Callout : Brief Summary
HTTP Callout enables us to firmly integrate our Apex code with an external web service/API. By The Callout we send an HTTP request from our apex class code, and then receives the response from external web service.
HTTP callouts can be used with any HTTP service, either SOAP or REST.
In this example we will create a lightning component. by this component we make a HTTP callout and send a GET request(Retrieve data identified by a URL) to a web service to get the foreign exchange rates. The foreign exchange rates service sends the response in JSON format. and then we display the response data on our lightning component.
For foreign exchange rates reference: http://fixer.io/
Before you run the example in this Post, you’ll need to Authorize the endpoint URL of the Callout :
http://api.fixer.io
Step 1 : Authorize the endpoint URL For Apex Callout.
For Authorize the endpoint URL -:
- From Setup, enter Remote Site Settings in the Quick Find box
- Click on the Remote Site Settings.
- Click New Remote Site.
- For the remote site name, enter foreign_exchange_rates .
- For the remote site URL, enter http://api.fixer.io ,This URL authorizes all subfolders for the endpoint, like http://api.fixer.io/latest
- Make sure your Active checkbox is Equal to True.
- Click Save.
Fixer.io is a free JSON API for current and historical foreign exchange rates published by the European Central Bank.
The rates are updated daily around 4PM CET.
Here is the snapshot of Response (JSON format), who coming from web service callout (http://api.fixer.io) in This Example..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
{ "base": "USD", "date": "2016-12-30", "rates": { "AUD": 1.3847, "BGN": 1.8554, "BRL": 3.2544, "CAD": 1.346, "CHF": 1.0188, "CNY": 6.9445, "CZK": 25.634, "DKK": 7.0528, "GBP": 0.81224, "HKD": 7.7555, "HRK": 7.1717, "HUF": 293.93, "IDR": 13446, "ILS": 3.84, "INR": 67.919, "JPY": 117.07, "KRW": 1204.2, "MXN": 20.654, "MYR": 4.486, "NOK": 8.62, "NZD": 1.438, "PHP": 49.585, "PLN": 4.1839, "RON": 4.306, "RUB": 61, "SEK": 9.0622, "SGD": 1.4452, "THB": 35.79, "TRY": 3.5169, "ZAR": 13.715, "EUR": 0.94868 } } |
Step 2 : Create Apex Class For Make HTTP Callouts.
Apex class [httpCallOutCtrl.apxc]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class httpCallOutCtrl { // Pass in the endpoint to be used using the string url @AuraEnabled public static Map < String, Object > 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); System.debug('response:--> ' + res.getBody()); // Deserialize the JSON string into collections of primitive data types. Map < String, Object > resultsMap = (Map < String, Object > ) JSON.deserializeUntyped(res.getBody()); system.debug('resultsMap-->' + resultsMap); return resultsMap; } } |
-
- In above apex class controller we have a getCalloutResponseContents @AuraEnabled class method with one parameter url as string type. And the Return type is Map type where String is key and object as value of the Map.
- In getCalloutResponseContents Method ,first we created a new HTTP object. and set the EndPoint url with url parameter.
- In the url parameter we set url from lightning component js controller.
- and when the HttpResponse come from callout, Deserialize the JSON string into the Map collection and return the map.
Step 3 : Create Lightning Component
Component [SampleComponent.cmp]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<aura:component controller="httpCallOutCtrl"> <aura:attribute name="response" type="Map"/> <aura:attribute name="ListOfCurrency" type="String[]"/> <div class="slds-m-around--medium"> <!--Header part--> <div class="slds-page-header" role="banner"> <div class="slds-media__body"> <p class="slds-page-header__title slds-truncate" title="foreign exchange rates">foreign exchange rates By HTTP Callouts</p> <lightning:button variant="brand" label="Make CallOut" onclick="{! c.calloutCtrl }" /> </div> </div> <!--Header part close--> <h3 class="slds-section-title--divider"> Base : {!v.response.base}</h3> <h3 class="slds-section-title--divider"> Date : {!v.response.date}</h3> <!--iterate the list of Currency--> <ul class="slds-list--dotted"> <aura:iteration items="{!v.ListOfCurrency}" var="rateLst"> <li>{!rateLst}</li> </aura:iteration> </ul> </div> </aura:component> |
- In above Lightning component we are use two aura:attribute one is type of map and one is type of array of String
For How to use Map in lightning component : Click here…
JS controller [sampleComponentController.js]
1 2 3 4 5 6 7 8 9 10 11 12 13 |
({ calloutCtrl : function(component, event, helper) { // Rates are quoted against the Euro by default. // Quote against a different currency by setting the base parameter in your request. var base = 'USD'; helper.getResponse(component, base); }, }) |
- In js controller we set ‘USD’ as base parameter. and pass it to JS helper function.
JS Helper [sampleComponentHelper.js]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
({ getResponse: function(component, base) { // create a server side action. var action = component.get("c.getCalloutResponseContents"); // set the url parameter for getCalloutResponseContents method (to use as endPoint) action.setParams({ "url": 'http://api.fixer.io/latest?base=' + base }); action.setCallback(this, function(response) { var state = response.getState(); if (component.isValid() && state === "SUCCESS") { // set the response(return Map<String,object>) to response attribute. component.set("v.response", response.getReturnValue()); // get the all rates from map by using key var getAllRates = component.get("v.response")['rates']; var CurrencyList = []; // play a loop on rates object for (var key in getAllRates) { // push all rates with there Name in CurrencyList variable. CurrencyList.push(key + ' = ' + getAllRates[key]); // i.e : INR = 67.919 } // set the CurrencyList to ListOfCurrency attribute on component. component.set("v.ListOfCurrency", CurrencyList); } }); $A.enqueueAction(action); }, }) |
Lightning App [TestApp.app]
1 2 3 4 5 6 7 8 |
<aura:application extends="force:slds"> <c:SampleComponent/> <!-- here c: is org. namespace prefix--> </aura:application> |
Output -:
Like our facebook page for new post updates.? & Don’t forget to bookmark this site for your future reference.
if you have any suggestions or issue with it, you can post in comment box. 🙂
14 comments
Good
Thanks Vamsee 🙂
That was awesome . Three cheers for sweet components.
Thanks for your feedback #Aman Rawat 🙂
But how do you write the test class for this?
check that link :
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
Just to confirm this callout is done via server side apex code and not client side javascript controller. I believe we cannot make API calls from Lightning JS controller.
what if i want to make the call from the js controller instead of going to the backend
Your post are amazing and very descriptive for anybody who want to learn Lightning 🙂
Thanks for your feedback.
Hi,
Thanks for this an awesome tutorial, it is very detailed and helpful.
When I press preview from app I can see the button saying make call. But after pressing this button I do not see the output as shown above. It remains the same. Please help.
What if I do Http Callout using SOAP instead of REST? Will that work in Salesforce one? As I’m only getting the HTML in the response and not JSON data.
As of March 6th 2018, the legacy Fixer API (api.fixer.io) is deprecated and a completely re-engineered API is now accessible at https://data.fixer.io/api/ The core structure of the old API has remained unchanged, and you will only need to perform a few simple changes to your integration.
By updating the below endpoint in the Remotesite setting what the changes we need to perform kindly provide the logic so that we can understand.
https://data.fixer.io/api/