How to Call Salesforce API from Lightning Component

You may have heard about that we can not make the Salesforce API Call directly from the lightning component. If you do make the callout from the lightning component then you will get the below error

INVALID_SESSION_ID:This session is not valid for use with the API.

For Example when you will execute the below code from the Developer Console then you will get the Valid Response


HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
HttpResponse resp = new HttpResponse();

req.setMethod('GET');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
resp = h.send(req);
System.debug('#### Response Status '+resp.getStatus());
System.debug('#### Response Status Code '+resp.getStatusCOde());
System.debug(resp.getBody());

But if you will call the same block from the Lightning Component then you will get INVALID_SESSION_ID:This session is not valid for use with the API. Error.

I gone through with this error and found THIS SALESFORCE DOCUMENT where they have specified why we can not make API Call from JavaScript Code.

After reading the document, I have come up with 2 Solutions that are given below: –

1 РConnected App and Named Credentials as Callout Endpoints and Auth Providers

2 – Using VF Page – VF page will be used to get the Session Id of the current log in user and this VF page will be used into Apex class for fetching the Session Id.

In this tutorial we will use VF page for making callout because it is an easy and simple method method. Follow the below steps

Step1 – Open Developer Console, File -> New -> VisualForce Page -> Enter Name “GetSessionIdVF” -> OK. Use below code for VF Page


<apex:page >
 Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

Step2 – Create a New Class which will use this VF page to get the Session Id and making API Call Out. File -> New -> Apex Class -> Name it “ApiCallLightningComponent” -> OK. Use below code for the class.


public class ApiCallLightningComponent {
 /*
 * @Name : - fetchUserSessionId
 * @Description: - Call the VF page and get the Log In Use Session Id
 * @Params : - none
 * @ReturnType : - String
 */
 public static String fetchUserSessionId(){
 String sessionId = '';
 // Refer to the Page
 PageReference reportPage = Page.GetSessionIdVF;
 // Get the content of the VF page
 String vfContent = reportPage.getContent().toString();
 System.debug('vfContent '+vfContent);
 // Find the position of Start_Of_Session_Id and End_Of_Session_Id
 Integer startP = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length(),
 endP = vfContent.indexOf('End_Of_Session_Id');
 // Get the Session Id
 sessionId = vfContent.substring(startP, endP);
 System.debug('sessionId '+sessionId);
 // Return Session Id
 return sessionId;
 }
 /*
 * @Name - makeAPICall
 * @Description - Responsible for making API Call out
 * @params - None
 * @ReturnType - String
 */
 @AuraEnabled
 public static String makeAPICall(){
 String sessionId = fetchUserSessionId();
 HTTP h = new HTTP();
 HTTPRequest req = new HTTPRequest();
 HttpResponse resp = new HttpResponse();
 req.setMethod('GET');
 req.setHeader('Authorization', 'Bearer ' + sessionId);
 req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v41.0/query?q=Select+Id,+Name+From+Account');
 resp = h.send(req);
 System.debug('#### Response Status '+resp.getStatus());
 System.debug('#### Response Status Code '+resp.getStatusCOde());
 System.debug(resp.getBody());
 return JSON.serialize(resp.getBody());
 }
}

See the comments.

ApiCallLightningComponent class contains 2 methods fetchUserSessionId and makeAPICall, One for getting the Session Id and Other for making the Callout that will be called from the JavaScript.

Step3 – Create a lightning component, File -> New -> Lightning Component -> Name it “MakiAPICall” -> OK. Use below code for the Component


<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes, flexipage:availableForRecordHome,force:hasRecordId, forceCommunity:availableForAllPageTypes, force:lightningQuickAction" controller="ApiCallLightningComponent" access="global" >
<div class="slds-m-around_x-small">
			<lightning:button variant="brand" label="Make CallOut" iconName="action:apex" iconPosition="left" onclick="{!c.doHandleClick }" /></div>
</aura:component>

Click on the Controller and use below code


({
doHandleClick : function(component, event, helper) {
helper.onHandleClick(component, event, helper);
}
})

Click on the helper and then use below code for helper


({
onHandleClick : function(component, event, helper) {
// Get the action of Controller (Apex) Class
var action = component.get('c.makeAPICall');

// set the callback which will return the response from apex
action.setCallback(this, function(response){
// get the state
var state = response.getState();
if( (state === 'SUCCESS' || state ==='DRAFT') && component.isValid()){
// get the response
var responseValue = response.getReturnValue();
// Parse the respose
var responseData = JSON.parse(responseValue);
alert(responseData);
//alert(responseData.totalSize);
console.log(responseData);
} else if( state === 'INCOMPLETE'){
console.log("User is offline, device doesn't support drafts.");
} else if( state === 'ERROR'){
console.log('Problem saving record, error: ' +
JSON.stringify(response.getError()));
} else{
console.log('Unknown problem, state: ' + state +
', error: ' + JSON.stringify(response.getError()));
}
});
// send the action to the server which will call the apex and will return the response
$A.enqueueAction(action);
}
})

Step4 – In Final Step Test the Component using Lightning Application. File -> New -> Lightning Application -> Enter Name -> Submit -> Use below Code


<aura:application extends='force:slds' >
<c:MakiAPICall/>
</aura:application>

Note: – If Your component name is different then use the name of your component instead of MakiAPICall.

Output of the above code

Call API From Lightning Component

You can find the complete Here.

Happy Learning ūüôā

Happy Coding ūüėČ

Sharing is Caring

Resources –

 

Advertisements

LinkedIn – Salesforce Integration

Hello All, I am back with another Integration post and in this post, I will show how you can connect with LinkedIn from your salesforce org using a small piece of code.

So, Get ready to do another integration with Salesforce.

Before we start playing with the code we need to create a Custom Setting where we will store Access Token and Expiry time so that we could use this while making the callouts.

Setup Custom Object: –

Go to Setup -> Create ->¬†Objects -> New -> Name it “LinkedIn Information

LinkedIn Informations

Create a VF page and Controller Class: –

Create an Apex class Name it “LinkedlnoAuthController

Go to Setup -> Develop -> Apex Classes -> New -> 

Next, Create a VF page that will do the Authorization with LinkedIn. Name it “LinkedlnoAuth“.

You will get the complete code from my GitHub Repo. Copy Apex Class and VF page code From Here.

After you created VF page Preview it, Copy the URL and paste somewhere into the notepad++ or any other text editor. URL will be something like below

https://dreamhouse-a-dev-ed–c.ap5.visual.force.com/apex/LinkedlnoAuth

Create an App in LinkedIn: –

Time to create a Connected App into LinkedIn developer account to get the Client Id (Consumer Key)  and Client Secret(Consumer Secret).

Go to LinkedIn Developer Console Create Application. Refer this link to get the complete picture of app configuration. You will get Client Id and Client Secret copy both and store in the text editor.

You LinkedIn app page will look like below

LinkedIn - Application

Make Required Changes into Apex Class: –

1 РOpen LinkedlnoAuthController class replace redirect_URI with your VF page preview URI (line #10).

2 РReplace consumerKey with your client Id and consumerSecret with your Client Secret (line #8 and #9).

Now, we are all set to let’s do some testing and see if we have successfully integrated LinkedIn with Salesforce.

Open LinkedlnoAuth VF page and preview it. Click Connect with LinkedIn button, it will open a new screen asking your LinkedIn username and password

Connect with Linkedln

Linked Login

Enter your username and password then sign in Grant permission to Application -> Click Complete Authorization, a success message will show.

Linked Login.png

Now Click on Get Basic Info -> A basic information will show here in PAGE

Basic Info.png

Facing any issue let me know in the comment section.

Happy Coding ūüôā Enjoy Coding ūüôā

Salesforce – Google Calendar Integration tips and tricks

Hello friends, In this post, I will show you how you can integrate Salesforce with Google Calendar so that Salesforce user could aware of all upcoming events and tasks!

Below is the list of all the tasks that we will do in this post to do Integrate Google Calendar with Salesforce.

  1. Create a public List type Custom SettingGoogleCalenderInfo” to store the access/refresh token and expiry time (in Seconds).
  2. Enable Google Calendar API and create an App to get the Consumer Key and Consumer Secret
  3. Create VF page Apex Class to make the callout and store Access/Refresh Token into Custom Setting.
  4. Create Another VF page which will fetch all the List of Calendar Available into your Calendar and create a new Calendar From Salesforce.

Create New Custom Setting: –

Login into Your Salesforce Org and go to Setup -> Develop -> Custom Settings -> New

See below image for the field names and data types

Custom Setting

Create Required VF pages and Apex Classes: –

  • Open Developer Console and Create¬†2 Apex Classes¬†GoogleCalenderApi and¬†GoogleCalendarActionsController.
  • Now, Create 2 VF pages “GoogleCalendarActions” and “GoogleCalenderoAuth”
  • You will get the Complete code for All the pages and Apec Classes From Here¬†copy the code and paste in your pages/classes.

Do Enable Google Calendar API and Settings: –

Go to  Using OAuth 2.0 to Access Google APIs and you will get Detailed Information about authentication process.

Go to Google API Console, Credentials -> Create Credentials -> oAuth Client Id

1

Application Type -> WEB

Authorized redirect URIs -> URL To Your VF page “You already have created the VF page if not follow the above steps and create both the pages with classes”

Open “GoogleCalenderoAuth” VF page, Click Preview and Copy the URL that URL is the Redirect¬†URI paste that URL here.

Note: – You also need to replace “redirect_uri” variable in GoogleCalendarAPI class with your VF page URL.¬†

VF PAGE Preview.png

Now, Click Create, a Pop up with Client Id and Client Secret will open

2

3

Copy both Client Id and Client Secret in any text Editor like notepad++, notepad, or any editor.

Now, Open GoogleCalenderApi class replace consumerKey with your Client Id and clientSecret with your Client Secret.

Now, as we have done all the necessary steps and it’s show time.

Open “GoogleCalenderoAuth” VF page, preview it Page will look like below

VF page.png

Click “Connect With Calendar” you will be redirected to Gmail Login, Login with your Gmail, Grant Access to Application. You will get back to the same Page and Now Click “Get Access Token” a new Page “GoogleCalendarActions” will open.

VF page.png

VF page

First, we will create a New Calendar, Enter “Testing Google API ”¬†and then Create New Calendar. You will get a Success Message with the response.

Create New Calendar

Now, List All Calendars will list all the calendars that are available to your Account.

List All Calendars.png

Note: – Using the Above Code of “GoogleCalenderoAuth” Page and “GoogleCalenderApi” Apex Class you can integrate with Any Google API. You only need to make a minor change which is the value of the calendar_Scope variable in¬†GoogleCalenderApi class, use the scope of the API that you want to Connect. You will get the scope of all the APIs OAuth 2.0 Scopes for Google APIs.

Any Queries come in the comment section.

 

Create Anonymous Salesforce Apex REST API with Force.com Platform

The Force.com REST API lets you integration with Force.com applications using standard HTTP methods. Using Apex REST you can expose the data that resides into your Salesforce instance and you can also get the data directly from the other system which hits the particular URL.

You can use below HTTP methods to expose the Salesforce data and vice versa

GET, POST, DELETE, PUT and HEAD, PATCH

In this post, I’ll show you how to create an Apex Rest API which will expose Salesforce data which do not require authentication.

We will use Salesforce Site to create the API, using site will let us use APEX REST without authentication from any platform.

1 – Create a new Custom Object for this tutorial. Setup -> Create -> Objects -> New Custom Object -> Create New Object Student

1

2 – Now, we will create an Apex Class which will expose Student__c Object. Setup -> Develop -> Apex Classes -> New and copy the Apex code from Here and paste into Editor.

3 РNow, time to create a Salesforce Site. Setup -> Develop -> Sites. You will need a domain for the site and I will use studentAPI (You need to enter a valid domain) and Check Availabilty. Check  I have read and accepted the Force.com and then Register My Force.com Domain.

2

4 – Click New to create new Site

3

5 – After Saving You will be redirected to Site Detail Page which will look like below and Click on “Public Access Settings”

4

public access setting – Settings which can be access publically without login credentials. So, We will add our Apec Class in public access settings.

6 – Find “Enabled Apex Class Access”

5

7 – Edit, Find StudentController in Available Apex Classes and then Add into Enabled Apex Classes then Save it.

6

8 РTime to give permission to the Object (Student__C) that we have created earlier in the tutorial. Edit the Profile and find Student Object under Custom Object Permissions provide Read, Create, Edit and Delete Permission to Student Object. Save the Profile.

7

8

9 РNow time is to test the APEX REST API. We will use https://www.hurl.it/ tool to test the same.

10 – Before we go for testing, we will need Endpoint URL to hit the APEX REST. For this, go to Setup -> Develop -> Sites -> Copy Site URL and paste into Notepad or any editor.

9

Note: – Site URL must be started with https no matter what is shown.

11 РWe have copied the Site URL, however, this is not the complete. We will need to add some extra string that we used in our Apex class with services/apexrest/. Open apex class and copy the string after urlMapping. 

10

12 РNow, we will create the complete URL which will look like the combination of Site URL + /services/apexrest/ + Urlmapping String. After you will merge all three string URL will look like

https://studentapi-developer-edition.ap4.force.com/services/apexrest/v1/Students/

12 РTime for some magic open https://www.hurl.it/. Select Post For Method, Paste the complete URL. Headers РAdd content Type as JSON. Click add body and use JSON for the body. Launch Request to create Student into Salesforce

{
“Name” : “Anonymous Student”
}

11.png

13 – You will get the response like below after successful creation of the record.

12.png

14 – Open Salesforce, go to student object and you will get the record there

13

15 – We have created Student record, now let’s fetch that record using the API. Create request like below and then launch request.

14.png

Response will be like below

15

 

Hope you enjoyed reading. If you have any question or issue please let me know in the comment section.

Resources: –

An_Introduction_to_Force.com_Sites