Invoking REST API From Visualforce Page

Usually we make Rest API calls from Salesforce to External systems to get the data or to pass the updates to External Systems, using Apex class. But sometimes we can have a situation, like where we need to make a call to external systems from the visual force page.

Salesforce has introduced a concept called AJAX ToolKit, which help us to make REST API call from the JavaScript in Visualforce Page. Here is an example to invoke REST API from Visualforce Page. In below example I’m using https://exchangeratesapi.io/ web service HTTP callout and send a GET request to get the foreign exchange rates. The foreign exchange rates service sends the response in JSON format.

Visualforce Page:

<apex:page>
    <apex:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
    <script>
    function apiCall() {
        //Get a reference to jQuery that we can work with
        $j = jQuery.noConflict();
        //endpoint URL
        var weblink = 'https://api.exchangeratesapi.io/latest?base=USD'; 
        
        $j.ajax({
            url: weblink,
            type: 'GET', //Type POST or GET
            dataType: 'json',
            beforeSend: function(request) {
                //Add all API Headers here if any
                //request.setRequestHeader('Type','Value');
            },
            
            crossDomain: true,
            //If Successfully executed 
            success: function(result) {
                //Response will be stored in result variable in the form of Object.
                console.log('Response Result' + result);
                
                //Convert JSResponse Object to JSON response
                var jsonResp = JSON.stringify(result);
                document.getElementById("apiData").innerHTML = jsonResp;
            },
            
            //If any Error occured
            error: function(jqXHR, textStatus, errorThrown) {
                //alert('ErrorThrown: ' + errorThrown);
            }
        });
    }
    </script>
    <apex:form>
        <!--call javaScript-->
        <input type="button" value="Call API" onclick="apiCall()" />
        <div id="apiData">
        </div>
    </apex:form>
</apex:page>

  • ADKFurry

    When using a different URL that returns a JSON object contained within a leading “[” and a trailing “]” the code fails. Maybe the JSON is being treated as a list or array, and that’s not accounted for in your code?

    Quick sample of what is being returned, for processing:

    [{“Id”:”6XkQ1″,”UserName”:”email1″,”FirstName”:”fname1″,”LastName”:”lname1″,”Active”:true,”Email”:”email1″,”AccessLevel”:”Learner”,”Brand”:”Default”},{“Id”:”6XkQ2″,”UserName”:”email2″,”FirstName”:”fname2″,”LastName”:”lname2″,”Active”:true,”Email”:”email2″,”AccessLevel”:”Learner”,”Brand”:”Default”}]

    The exchange rates JSON returned isn’t contained in brackets…that seems the only difference.

    Thank for any assistance.

  • Siddhartha Charles Xaviers Gho

    Hi Biswajeet,

    The code is simply not working.
    Could you please update the code….
    When I click on the call API button nothing simply happens.

    Regards,
    Siddhartha

    • Hi Siddhartha,

      That previous API was not working, they have changed the URL. Now I’m using a new URL, it is working.

  • suren

    Hi Biswajeet,

    Nice post. I have few queries.

    Is this count against API request limit?

    Usually we add the endpoint URL in remote site settings but how this fixer URL is working without adding?

    Can we access the endpoint URL which is restricted by IP?

    Regards,
    Suren

    • Hi Suren,

      No need to add the URL in remote site settings.