Make HTTP callout from Lightning Component and show data on UI. (Using Apex Parser)

Posted on April 18, 2020 Post Thumbnail

Hey Trailblazers, In this blog we are going to create a lightning component which going to make an external API  callout to verify email Id and shows result to the UI.

In our previous blog post, We created this component by using ( JS Object ) and in this blog post we're going to use ( Apex parser ) to get specific values from Api response.

For getting API Key of third party Service, Have a look on my previous Blog Post.

Make HTTP callout from Lightning Component and show data on UI. (Using JS Object)

https://heysalesforce.org/posts/make-http-callout-from-lightning-component-and-show-data-on-ui-using-js-object

Let's create Aura component.

millionVerifier.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="MillionVerifierCtrl">
    <aura:attribute name="email" type="String"/>
    <aura:attribute name="apiKey" type="String" default="NhX3FJkuk4Rf5imvrg4XTCdYA"/>
    <aura:attribute name="result" type="String"/>
    <aura:attribute name="credits" type="Integer"/>
    <div class="slds-box">
        <div class="slds-box">
            <img src="{!$Resource.heySfLogo}"/>
            <h1>Email Verifier ( Using Apex Parser )</h1>
            <lightning:input aura:id="email"
                             type="email"
                             label="Email Id"
                             value="{!v.email}">
            </lightning:input>
            <lightning:input aura:id="apiKey"
                             type="String"
                             label="Api Key"
                             value="{!v.apiKey}">
            </lightning:input>
            <br/>
            <lightning:button variant="brand" 
                              label="Verify Email" 
                              title="Brand action" 
                              onclick="{! c.handleClick }" />
        </div>
        <div class="slds-box">
            <h2 aura:id="color" class="">Result : {!v.result}</h2>
            <h2>Credits Left : {!v.credits}</h2>
        </div>
    </div>
</aura:component>

millionVerifierController.js

({
    handleClick : function(component, event, helper) {
        var email = component.get("v.email");
        var apiKey = component.get("v.apiKey");
        var url = "https://api.millionverifier.com/api/v3/?" ;
        var apiUrl = url +"api=" +apiKey +"&email="+email+"&timeout=10";
        var action = component.get("c.getCalloutResponse");
        action.setParams({
            "mainUrl":apiUrl
        });
        action.setCallback(this, function(response) {
            console.log(response.getReturnValue());
            var res = response.getReturnValue();
            component.set("v.credits",res[1]);
            component.set("v.result",res[0]);
            var cmpColor = component.find('color');
            if(res[0]=="ok")
            {
                $A.util.addClass(cmpColor, 'gre');
                $A.util.removeClass(cmpColor, 'red');
            }
            if(res[0]=="invalid")
            {
                $A.util.addClass(cmpColor, 'red');
                $A.util.removeClass(cmpColor, 'gre');
            }
        });
        $A.enqueueAction(action);
    },
}
)

millionVerifier.css

.THIS {
    margin: 0.5% 0.2%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    background-color: #fafdfd;
}
.THIS h1 {
    font-size:150%;
}
.THIS .gre {
    color:green;
    background-color: #defae2 ;
}
.THIS .red {
    color:red;
    background-color: #f7cbd1 ;
}
.THIS img {
    width:60%
}

Apex Controller : MillionVerifierCtrl

public class Miri_MillionVerifierCtrl {
    @AuraEnabled
    public static list<String> getCalloutResponse(String mainUrl) {
        list<String> resList = new list<String>();
        String result;
        String result1;
        // 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(mainUrl);
        req.setMethod('GET');
        
        // Send the request, and return a response
        HttpResponse res = h.send(req);
        //System.debug('response:--> ' + res.getBody());
        JSONParser parser =  JSON.createParser(res.getBody());
        while (parser.nextToken() != null) {
            if(parser.getText() == 'result') 
            {
                System.debug('Main Result'+ parser.getText());
                system.debug('Main Parser-->' + parser.nextValue());
                result = parser.getText();
                resList.add(result);
            }
            if(parser.getText() == 'credits') 
            {
                System.debug('Main credits'+ parser.getText());
                system.debug('Main credits-->' + parser.nextValue());
                result1 = parser.getText();
                resList.add(result1);
            }
            
            //System.debug('Current token: ' + parser.getCurrentToken());
            //    system.debug(parser.getText());
        }
        // system.debug('Parser-->' + parser.nextValue());
        String fieldName = parser.getCurrentName();
       
        return resList;
    }
}

Let's test this component :

As you can see, Right one component is working perfectly along with left one which was created using ( JS Object )

Thank you :)


1407
0

Tags: #salesforce #lightningComponent #httpCallout #apexParser

Comments

There are no comments yet.
Your message is required.

Get notified of new posts