How to call an external REST API to get data from API and passing the variables from REST API to apex method in Salesforce using Apex REST Post Methods | How to pass variables from REST API to Apex in Salesforce

2,425 views


Hey guys, today in this post we are going to learn about How to call an external REST API to get data from API and passing the variables from REST API to apex method and inserting a record into custom object in Salesforce using Apex REST Post Methods.

This example we are passing the variables from REST API to apex method and putting the value into custom object’s fields that is returns from API Using Apex REST post method.

To access the external REST API, First we need to Adding the Remote Site Settings

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
   

Follow the Steps:-

Setup ➑ Remote Site Settings ➑ Remote Site Name ➑ Enter the URL for the remote site

Files we used in this post example

restApiPostMethodCmp.cmp Lightning Component It is used to get data from API and passing the variables from REST API to apex method in salesforce.
restApiPostMethodCmpController.js JavaScript Controller File It is hold Javascript calloutCtrl function.
restApiPostMethodCmpHelper.js JavaScript Controller Helper File It is hold Javascript Helper getResponse function to get data from API calling through apex class method.
restApiPostMethodCmpCtrl.apxc

Apex Class Controller It is used to get data from API and passing the variables from REST API to apex method through Rest Apex class method.
Custom Object

Object Name:- Pan_Verification__c
Object’s Fields Name:- API_Name__c, Application_Number__c, Success_Status__c, Process_Status__c, Pan_Number__c, DOB__c, User_Name__c

Final Output

rest api get method example in salesforce -- w3web.net

 

You can download file directly from github by Click Here.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

 

Other related post that would you like to learn in Salesforce

 

Find the below steps:-

Create Lightning Component

Step 1:- Create Lightning Component : restApiPostMethodCmp.cmp

From Developer Console >> File >> New >> Lightning Component

restApiPostMethodCmp.cmp [Lightning Component File]

  1.    <aura:component controller="restApiPostMethodCmpCtrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
  2.     <aura:attribute name="response" type="Map"/>
  3.     <aura:attribute name="panResponse" type="Pan_Verification__c"/>    
  4.     <aura:attribute name="mySpinner" type="boolean" default="false"/>
  5.  
  6.     <div class="slds slds-p-around--medium">
  7.         <div class="slds-section__title-action slds-p-around--small">
  8.             <h2><strong>Uses of Apex REST Post Methods</strong></h2>
  9.         </div>
  10.  
  11.         <div class="slds-grid slds-wrap">
  12.  
  13.             <div class="slds-col slds-size_4-of-12 slds-p-horizontal--small slds-m-bottom--small">                
  14.                 <div class="slds-form-element">
  15.                     <label class="slds-form-element__label">Name</label>
  16.                     <div class="slds-form-element__controller">
  17.                         <ui:inputText class="slds-input" aura:id="userName"/>
  18.                     </div>
  19.                 </div>
  20.             </div>
  21.  
  22.             <div class="slds-col slds-size_4-of-12 slds-p-horizontal--small slds-m-bottom--small">
  23.                 <div class="slds-form-element">                     
  24.                     <div class="slds-form-element__controller">         
  25.                         <lightning:input type="date" name="userDateBirth" label="Date Of Birth" aura:id="userDateBirth"/>                         
  26.                     </div>
  27.                 </div>
  28.             </div>
  29.  
  30.             <div class="slds-col slds-size_4-of-12 slds-p-horizontal--small slds-m-bottom--small">
  31.                 <div class="slds-form-element">
  32.                     <label class="slds-form-element__label">Pan Number</label>
  33.                     <div class="slds-form-element__controller">
  34.                         <ui:inputText class="slds-input" aura:id="panNumber"/>
  35.                     </div>
  36.                 </div>
  37.             </div>
  38.  
  39.         </div>
  40.         <div class="slds-text-align--center slds-m-top--medium slds-m-bottom--medium slds-p-horizontal--small">                 
  41.             <button class="slds-button slds-button--brand" onclick="{!c.calloutCtrl}">Submit</button>
  42.         </div>
  43.  
  44.         <br/><br/><br/>
  45.  
  46.         <table class="slds-table slds-table_bordered slds-table_col-bordered mystles" style="border:1px #ddd solid;">
  47.             <thead>
  48.                 <th>API Name</th>
  49.                 <th>Application Number</th>
  50.                 <th>Success Status</th>
  51.                 <th>Process Status</th>
  52.                 <th>Pan Number</th>
  53.                 <th>Name</th>
  54.                 <th>Date of birth</th>
  55.             </thead>
  56.             <tbody>
  57.                 <tr> 
  58.                     <td>{!v.panResponse.API_Name__c}</td>
  59.                     <td>{!v.panResponse.Application_Number__c}</td>
  60.                     <td>{!v.panResponse.Success_Status__c}</td>
  61.                     <td>{!v.panResponse.Process_Status__c}</td>
  62.                     <td>{!v.panResponse.Pan_Number__c}</td>
  63.                     <td>{!v.panResponse.User_Name__c}</td>
  64.                     <td>{!v.panResponse.DOB__c}</td>
  65.                 </tr>    
  66.             </tbody>
  67.         </table>
  68.  
  69.         <aura:if isTrue="{!v.mySpinner}">
  70.             <section class="slds-modal slds-fade-in-open" aura:id="modalFade">
  71.                 <div class="slds-spinner_container">
  72.                     <div role="status" class="slds-spinner slds-spinner_medium slds-spinner_brand">
  73.                         <span class="slds-assistive-text">Loading</span>
  74.                         <div class="slds-spinner__dot-a"></div>
  75.                         <div class="slds-spinner__dot-b"></div>
  76.                     </div>
  77.                 </div>
  78.             </section>
  79.             <div class="slds-backdrop slds-backdrop_open"></div>
  80.         </aura:if>
  81.  
  82. <br/><br/>
  83.    <!--Start RelatedTopics Section-->
  84. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  85.  
  86.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  87.  
  88.             <br/><br/>
  89.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like β†’</span> </strong></p>
  90.             <div style="display:block; overflow:hidden;"> 
  91.                 <div style="width: 50%; float:left; display:inline-block">
  92.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  93.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  94.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  95.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  96.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  97.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  98.                     </ul>
  99.             </div>
  100.  
  101.             <div style="width: 50%; float:left; display:inline-block">
  102.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  103.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  104.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  105.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  106.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  107.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  108.                     </ul>
  109.                 </div>
  110.                <div style="clear:both;"></div> 
  111.                <br/>
  112.                 <div class="youtubeIcon">
  113.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  114.                 </div>
  115.     </div>
  116.  
  117. </div>
  118.  
  119.   <!--End RelatedTopics Section-->
  120.  
  121.     </div>
  122. </aura:component>

Create Component JavaScript Controller

Step 2:- Create Lightning Component : restApiPostMethodCmpController.js

From Developer Console ➑ File ➑ New ➑ Lightning Component ➑ JavaScript Controller

restApiPostMethodCmpController.js [JavaScript Controller]

  1.    ({
  2.  
  3.     calloutCtrl : function(component, event, helper) {        
  4.         helper.getResponse(component, event, helper);
  5.     },
  6.  
  7.  
  8. })

Create Component JavaScript Helper

Step 3:- Create Lightning Component : restApiPostMethodCmpHelper.js

From Developer Console ➑ File ➑ New ➑ Lightning Component ➑ JavaScript Helper

restApiPostMethodCmpHelper.js [JavaScript Helper File]

  1.    ({
  2. 	getResponse: function(component, event, helper) {             
  3.         var action = component.get("c.getPanVerification");        
  4.         var appNumberVal = "100";
  5.         var userName = component.find('userName');
  6.         var userNameVal = component.find('userName').get('v.value');
  7.         var userDateBirth = component.find('userDateBirth');
  8.         var userDateBirthVal = component.find('userDateBirth').get('v.value');
  9.         var panNumber = component.find('panNumber');
  10.         var panNumberVal = component.find('panNumber').get('v.value');
  11.        // alert('userDateBirthVal ' + userDateBirthVal);
  12.  
  13.  
  14.         action.setParams({          
  15.             "url": 'http://test.com/api/restApiPostMethodRemote',
  16.             "nameStr":userNameVal,
  17.              "dobStr":userDateBirthVal,
  18.              "panStr":panNumberVal
  19.         });
  20.  
  21.         component.set("v.mySpinner",true);
  22.  
  23.         action.setCallback(this, function(response) {
  24.             var state = response.getState();
  25.             // alert('state_1 ' + state );
  26.             if (state === "SUCCESS") { 
  27.                 component.set("v.mySpinner",false);                
  28.                 var results = response.getReturnValue();
  29.                 var getResponse = JSON.stringify(results);
  30.                 alert('AAAA' + JSON.stringify(results));
  31.                  component.set("v.response", getResponse);    
  32.                  component.set("v.panResponse", results);     
  33.                  //var getAllValue = component.get("v.response")["apiName"];
  34.                 // console.log('getAllValue ' + getAllValue);
  35.                  console.log('getResponse ' + getResponse);                
  36.  
  37.             }
  38.             else if(state === "ERROR"){
  39.                 component.set("v.mySpinner",false);
  40.             }
  41.         });
  42.  
  43.         $A.enqueueAction(action);
  44.     },
  45.  
  46.  
  47.  
  48. })

Create Apex Class Controller

Step 4:- Create Apex Class : restApiPostMethodCmpCtrl.apxc

From Developer Console ➑ File ➑ New ➑ Apex Class

restApiPostMethodCmpCtrl.apxc [Apex Class Controller]

  1.     @RestResource(urlMapping='/restApiPostMethodRemote/') 
  2. global WITH sharing class restApiPostMethodCmpCtrl {
  3.   @AuraEnabled
  4. 	global static Pan_Verification__c getPanVerification(String url, String nameStr, String dobStr, String panStr) {
  5.          Pan_Verification__c panObj = NEW Pan_Verification__c();
  6. 		// Instantiate a NEW http object
  7. 		Http h = NEW Http();
  8.  
  9. 		// Instantiate a NEW HTTP request, specify the method (GET) AS well AS the endpoint
  10. 		HttpRequest req = NEW HttpRequest();
  11.  
  12. 		req.setEndpoint(url);
  13.         req.setTimeout(120000);
  14. 		req.setMethod('POST');
  15.         req.setHeader('Content-Type', 'application/json;charset=UTF-8');     
  16.         req.setHeader('Subscription-key', '12tcasAPI96Lpmakm');         
  17.  
  18.         req.setBody('{"callBackEndPoint" : null,"apiName": "pan-Verification","requestBody": {"applicantDetails": {"consent": "Y","dateOfBirth": "'+ dobStr +'","applicantName": "'+nameStr+'","panNumber": "'+ panStr +'"},"applicationDetails": {"applicationNumber": "100"}}}');
  19. 		// Send the request, AND RETURN a response
  20. 		HttpResponse res = h.send(req);
  21. 		System.debug('response:--> ' + res.getBody());
  22.  
  23. 		// Deserialize the JSON string INTO collections OF primitive DATA types.
  24. 		Map < String, Object > resultsMap = (Map < String, Object > ) JSON.deserializeUntyped(res.getBody());
  25.         Map<String, Object>  resultsBody = (Map<String, Object>) resultsMap.get('responseBody');
  26.         Map<String, Object>  resultsProData = (Map<String, Object>) resultsBody.get('processData');
  27.  
  28. 		system.debug('resultsProData$$$$2 ' + resultsProData);
  29.         string apiStr = String.valueof(resultsMap.get('apiName'));
  30.         string applicationNumberStr = String.valueof(resultsMap.get('applicationNumber'));
  31.         string successStr = String.valueof(resultsMap.get('success'));
  32.         string processStatusStr = String.valueof(resultsBody.get('processStatus'));
  33.         string processDataPanStr = String.valueof(resultsProData.get('pan'));
  34.         string processDataNameStr = String.valueof(resultsProData.get('name'));
  35.         string processDataDobStr = String.valueof(resultsProData.get('dob'));
  36.         panObj.API_Name__c = apiStr;
  37.         panObj.Application_Number__c = applicationNumberStr;
  38.         panObj.Success_Status__c = successStr;
  39.         panObj.Process_Status__c = processStatusStr;
  40.         panObj.Pan_Number__c = processDataPanStr;
  41.         panObj.DOB__c = processDataDobStr;
  42.         panObj.User_Name__c = processDataNameStr;
  43.         INSERT panObj;
  44.         system.debug('panObj#### ' + panObj);
  45. 		RETURN panObj;
  46. 	}
  47.  
  48.  
  49. }

Create Lightning Application

Step 5:- Create Lightning Application : restApiPostMethodApp.app

From Developer Console ➑ File ➑ New ➑ Lightning Application

restApiPostMethodApp.app [Component Application File]

  1.   <aura:application extends="force:slds">
  2.     <c:lwcResetForm/>
  3. </aura:application>

rest api get method example in salesforce -- w3web.net

 

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

How do you call an API in Salesforce?

To call third-party APIs from your component's JavaScript code, add the API endpoint as a CSP Trusted Site. To call Salesforce APIs, make the API calls from your component's Apex controller. Use a named credential to authenticate to Salesforce.

How do you call an external service from Salesforce?

Connect your Salesforce org to an external API using zero lines of code. Use declarative tools and OpenAPI specifications to describe the external API functionality, and External Services creates invocable actions within Salesforce. Use the invocable actions to create a flow that interacts with the external API source.

Can we call API from trigger in Salesforce?

The trigger will make a REST API call to Salesforce and will insert/update the record in the 'Account' object in Salesforce.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses β†’

πŸ‘‰ Get Free Course β†’

πŸ“Œ Salesforce Administrators

πŸ“Œ Salesforce Lightning Flow Builder

πŸ“Œ Salesforce Record Trigger Flow Builder

πŸ‘‰ Get Free Course β†’

πŸ“Œ Aura Lightning Framework

πŸ“Œ Lightning Web Component (LWC)

πŸ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment