In this blog we are going to learn about how to make callout in @AuraEnabled method. When we use UserInfo.getSeessionId() method for authentication is throws exception “Invalid Sesssion_Id“. To avoid this exception and to make callout sucessfully from @AuraEnabled class, we need to pass a valid session id. Let’s learn how to do this.

Example

#Step 1:  First, create an visualforce page  named “sessionIdVfPage” and get the session id using $Api.Session_ID as metioned below code.

<apex:page >    
<!--         
/**        
* Webkul Software.
* @category  Webkul 
* @author    Webkul
* @copyright Copyright (c) 2010-2017 Webkul Software Private Limited (https://webkul.com)        
* @license   https://store.webkul.com/license.html 
*/  -->   
 Session_Id_Start_Here{!$Api.Session_ID}Session_Id_End_Here
</apex:page>

#Step2: Now create apex class

public class restCalloutMethod {
 /**
 * Webkul Software.
 *
 * @category Webkul
 * @author Webkul
 * @copyright Copyright (c) 2010-2018 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */ 
 
  public static String getSessionIdFrmVFPg(PageReference vfPageContainSessionId){
       String data = vfPageContainSessionId.getContent().toString();
       return data.substring(data.indexOf('Webkul_Session_Id_Start_Here') + 'Webkul_Session_Id_Start_Here'.length(), data.indexOf('Webkul_Session_Id_End_Here'));
  }
  @AuraEnabled
  public static Integer tr()
  {
        Integer tr = 0;
        try{
            HttpRequest req = new HttpRequest();
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v20.0/query/?q=SELECT+count()+from+Account');
            req.setMethod('GET');
            String sessionId = restCalloutMethod.getSessionIdFrmVFPg(Page.containSessionId); 
            String autho ='Bearer '+ sessionId;
            req.setHeader('Authorization', autho);
            Http http = new Http();
            HTTPResponse res = http.send(req);
            string response = res.getBody();
            tr= Integer.valueOf(response.substring(response.indexOf('totalSize":') + 11, response.indexOf(','))); 
          } catch(Exception ex){
            system.debug(ex);
          }
          return tr;
   }
}
    
   
       
   
    

#Step3: Now create lightning component :

<aura:component controller = "restCalloutMethod" >
 <!-- 
 /**
 * Webkul Software.
 *
 * @category Webkul
 * @author Webkul
 * @copyright Copyright (c) 2010-2018 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */ 
 -->
  <aura:attribute name="totalRec" type="Integer" ></aura:attribute>
  <aura:handler name="init" value="{!this}" action="{!c.accountList}"></aura:handler>
  <div class="slds-grid">
     <div class="slds-col slds-p-horizontal_small slds-size_1-of-2 slds-medium-size_5-of-6 slds-large-size_8-of-12">
     <div class="slds-page-header" role="banner">
 
     <div class="slds-grid">
        <lightning:icon iconName="standard:person_account" class="wk_person"/>
        <div class="slds-col">
            <h1 class="slds-text-heading--medium">Account </h1>
            <p class="slds-text-heading--label">Total Records : {!v.totalRec}</p>
        </div>
     </div> 
   </div>
  </div>
 </div>
</aura:component>

 

#Step4: Create client side controller :

({
  /**
    * Webkul Software.
    *
    * @category Webkul
    * @author Webkul
    * @copyright Copyright (c) 2010-2018 Webkul Software Private Limited (https://webkul.com)
    * @license https://store.webkul.com/license.html
    */ 
  accountList : function(component, event, helper) {
     helper.getTotalRec(component);
  },
})

#Step5: Create Helper Class :

            
({
  getTotalRec : function(component){
     var action = component.get("c.tr");
     action.setCallback(this, function(response){
     component.set("v.totalRec",response.getReturnValue());
      });
    $A.enqueueAction(action); 
   },
})

 

Output

Support

That’s all for how to make callout in @AuraEnabled method , still if you have any further query or seek assistance to make your salesforce classic apps compatible with lightning experience, feel free to contact us, we will be happy to help you https://wedgecommerce.com/contact-us/.

 

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home