Lightning Components with Integration

Api Used:

https://jsonplaceholder.typicode.com/ (Free api )

Remote Site Setting

Apex Class:

public class LearnREST {
	
    @AuraEnabled
    public static String getSpecificPost(Integer amount){
            
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint('https://jsonplaceholder.typicode.com/posts/'+amount);
        
        try{
            HttpResponse resp = h.send(req);
            
            if(resp.getStatusCode() == 200){
                return resp.getBody();
            }
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
        return '';
  }
    
    @AuraEnabled
    public static String getAllPost(){
            
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint('https://jsonplaceholder.typicode.com/posts');
        
        try{
            HttpResponse resp = h.send(req);
            
            if(resp.getStatusCode() == 200){
               return resp.getBody();
            }
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
        return '';
    }
    
    @AuraEnabled
    public static void getAllPic(){
        
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint('https://jsonplaceholder.typicode.com/photos');
        
        try{
            HttpResponse resp = h.send(req);
            
            if(resp.getStatusCode() == 200){
                System.debug(resp.getBody());
            }
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
    }
    
    @AuraEnabled
    public static void getSpecificData(Integer id){
        
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setMethod('GET');
        req.setEndpoint('https://jsonplaceholder.typicode.com/photos/'+id);
        
        try{
            HttpResponse resp = h.send(req);
            
            if(resp.getStatusCode() == 200){
                System.debug(resp.getBody());
            }
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
        }
    }
}
 
  

Test Class ( Not 100% completed )

@isTest
public class LearnRESTTest {

    @isTest static void testallpost(){
        Test.setMock(HttpCalloutMock.class,new HttpMock());
        LearnRest.getAllPost();
    }
    
    @isTest static void getAllPic(){
        Test.setMock(HttpCalloutMock.class,new HttpMock());
        LearnRest.getAllPic();
    }
}
 
  

Test Mock Class

@isTest
public class HttpMock implements HttpCalloutMock {

    public HttpResponse respond(HttpRequest req){
        
        
        HttpResponse rep=new HttpResponse();
        rep.setStatusCode(200);
        rep.setHeader('Content-Type', 'application/json');
        rep.setBody('{"a":"b"}');
        return rep;
    }
     
}
 
  

LearnRest.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="LearnREST">
	<aura:attribute name="list" type="String[]"></aura:attribute>
    <aura:handler name="Test" event="c:LearningInt" action="{!c.fire}"></aura:handler>
    
    <article class="slds-card slds-m-horizontal_large slds-m-top_large">
        
    	<div class="slds-card__body_inner">
           <c:GetInput></c:GetInput>
           <lightning:button variant="brand" title="Click" label="Click" class="slds-m-vertical_large" onclick="{!c.getData}"></lightning:button>
            		
          	<aura:if isTrue="{! !empty(v.list)}">
           		
                
               <div class="slds-grid">
                 
                   <aura:iteration items="{!v.list}" var="v">
                   <div class="slds-col" id="a">
                   		<p>{!v.id}</p>
                        <p>{!v.userId}</p>
                        <p>{!v.title}</p>
                       <p>{!v.body}</p><br/>
                   </div>
                   </aura:iteration>
                   	
               </div>
               
           </aura:if>

        </div>
    </article>
</aura:component>

LearnRestController.js

({
    fire:function(component,event,helper){
        if(!$A.util.isEmpty(event.getParam("val"))){
            
            var val =parseInt(event.getParam("val"));
       var obj = component.get("c.getSpecificPost");
        obj.setParams({
            "amount":val
        });
        obj.setCallback(this,function(resp){
            component.set("v.list",JSON.parse(resp.getReturnValue()));
        });
        $A.enqueueAction(obj);
        };
                    
       
    },
    
	getData : function(component, event, helper) {
		
        var action = component.get("c.getAllPost");
        action.setCallback(this,function(resp){
           	component.set("v.list",JSON.parse(resp.getReturnValue()));
            console.log(JSON.parse(resp.getReturnValue()));
        });
        $A.enqueueAction(action);
	}
})
 
  

LearnRest.css

.THIS #a{
	background-color:gray;
}
 
  

LearningInt.evt

<aura:event type="COMPONENT" description="Event template">
	<aura:attribute name="val" type="Integer"></aura:attribute>
</aura:event>
 
  

GetInput.cmp

<aura:component >
    <aura:attribute name="amount" type="String"></aura:attribute>
    <aura:registerEvent name="Test" type="c:LearningInt"></aura:registerEvent>
	<lightning:input value="{!v.amount}" label="Enter Search Amount" onchange="{!c.getNew}" ></lightning:input>
</aura:component>
 
  

GetInputController.js

({
	getNew : function(component, event, helper) {
		
        var value=component.get("v.amount");
        var eventval = component.getEvent('Test');
        eventval.setParams({"val":value});
        eventval.fire();
	}
})
 
  

Simple demonstration about the Rest integration with a external system and lightning component.


To view or add a comment, sign in

More articles by Sameera Sevindu De Silva

  • With Sharing and Without Sharing

    Apex runs in System context. By default apex is not considering about object level and field level permissions when…

  • Setting Record Create Page With Default Values

    Requirement: Opportunity can have multiple invoice records. When a new invoice record is creating…

  • Moving metadata between two unrelated Salesforce environments

    In situation where we want to migrate metadata between two related org we could use traditional change set but what if…

    2 Comments
  • OAuth 2.0 Demonstration

    Recently I was working in a integration project with constant contact V3 API to integrate with SalesForce. Initially I…

  • @testSetup method

    Creating a common method to create data will help to share record among multiple @isTest methods per class. Should be…

Others also viewed

Explore content categories