Sunday, April 8, 2018

Salesforce Lightning: Fetch data from an external API using Ajax


We will be using a very simple API which takes a GET request formatted as a certain URL, returning some random Chuck Norris jokes...lol, without requiring Apex code. So user will enter a number, and on click of Search button, will make a request to http://api.icndb.com/jokes/random/ API, get the response, parse it and display it on the page.

<aura:application extends="force:slds">

    <aura:attribute name="number" type="Integer" default="5"/>
    <aura:attribute name="html" type="String"/>

    <div class="slds-p-left_large">

        <h2 class="slds-text-heading_large">Chuck Norris Jokes Generator</h2>

        <lightning:input type="number"
                         aura:id="number"
                         label="Enter a number"
                         class="slds-m-around_small slds-size_1-of-8"/>

        <lightning:button variant="brand"
                          label="Get Jokes"
                          class="slds-m-around_medium"
                          onclick="{!c.handleClick }"/>

        <aura:unescapedHtml value="{!v.html}"/>

    </div>

</aura:application>
({
    handleClick : function(component, event, helper) {
        const number = component.find('number').get('v.value');

        if (number) {
            component.set('v.number', number);
            helper.handleAjaxRequest(component, event, helper);
        }

    }
})
({
    handleAjaxRequest : function(component, event, helper) {
        const xhr = new XMLHttpRequest();

        const number = component.get('v.number');

        const url = 'http://api.icndb.com/jokes/random/' + number;

        xhr.open('GET', url, true);

        xhr.onload = function() {
            if(this.status === 200) {
                const response = JSON.parse(this.responseText);

                let output = '<ul class=\'slds-list--dotted\'>';

                if(response.type === 'success') {
                    response.value.forEach(function(joke){
                        output += `<li>${joke.joke}</li>`;
                    });
                }

                output += '<ul>';
                component.set('v.html', output);
            }
        };

        xhr.send();
    }
})

The XHR object has properties and methods associated with it, one of which is open, where we specify type of request we want to make and the URL we want to make it to. The 3rd parameter is set as true as we want to make it asynchronous. The rest of the code is self-explainable.

As a last step, we need to add http://api.icndb.com as a trusted site or else our Lightning component will not be able to make a request and you will notice an error message in console something like this: Refused to connect to 'https://api.icndb.com/jokes/random/6' because it violates the following Content Security Policy directive:....."

So navigate to Setup → CSP Trusted Sites, and add the following entry.


That's it. Enjoy the jokes.

Now authentication is required for a lot of external APIs which are intricate ones using OAuth, and that can get complicated. So just remember that not all APIs give you as much freedom as they do here. You normally have to register your application with their systems and then you will have to authenticate. Different rules, different APIs.
Share This:    Facebook Twitter

2 comments:

  1. Hi Sonal,
    Thanks for sharing knowledge.
    Does it mean Ajax API request don't require authentication?

    ReplyDelete
    Replies
    1. As I said, not all APIs give you as much freedom as they do in the example. The API which I have used don't require authentication. But yes, for secured APIs, one should use Apex controller or else a user like me will use Chrome developer tool and can get the pasword or authentication key...lol

      Delete

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top