0

While doing my reading, I came across this link Lightning API calls

it says the following -


Make API calls from an Apex controller. You can’t make API calls from JavaScript code.


Question - Is it possible for me to read from and write to an external REST API from inside a Lightning component? Any sample code will be much appreciated.

1

This document goes into detail on how to call an external API from the Apex controller. https://developer.salesforce.com/page/Apex_Web_Services_and_Callouts

1
  • 2
    Thanks Tom, I should have been more clear in my question perhaps. I need to know how to make API call from Javascript inside lightning, not from APEX controller, If that is at all possible. [background] - I currently have visualforce pages where API call is made from Javascript and I am looking to convert those to lightning. thanks May 23 '16 at 23:26
1

It's now possible to call external API using JavaScript from within Salesforce Lightning.

You can use all the normal HTTP methods / verbs: GET, POST, PUT etc

Therefore, you should be able to read (GET) or write (PUT or POST).

Start by going to Setup → CSP Trusted Sites and adding your trusted site.

Which in this example is: https://api.postcodes.io/

Then use an approach like this:

({
    postcodeSearch : function(postcode) {
        var url = 'https://api.postcodes.io/postcodes/' + postcode;
        this.makeAjaxRequest(url);
    },
    callAjax : function(method, url, async, callback) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(component) {
            if (xmlhttp.readyState == 4 ) {
                callback.call(this, xmlhttp);
            }
        };

        xmlhttp.open(method, url, async);
        xmlhttp.send();
    },
    makeAjaxRequest : function(url) {
        this.callAjax("GET", url, true,
                      function(xmlhttp){
                          if (xmlhttp.status == 200) {
                              console.log(xmlhttp.responseText);
                          }
                          else if (xmlhttp.status == 400) {
                              console.log("makeAjaxRequest: 400 Error");
                          }else {
                              console.log("makeAjaxRequest: Error");
                          }
                      }
                     );
    }
})
0

In the above example from @Robs, you need to add the host https://api.postcodes.io to CSP Trusted Sites as well as Remote Site Settings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.