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.

3 Answers 3


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

  • 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, 2016 at 23:26

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;
    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);
    makeAjaxRequest : function(url) {
        this.callAjax("GET", url, true,
                          if (xmlhttp.status == 200) {
                          else if (xmlhttp.status == 400) {
                              console.log("makeAjaxRequest: 400 Error");
                          }else {
                              console.log("makeAjaxRequest: Error");

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .