Quantcast
Sunday , August 19 2018
Home / Apex / How To Do In Salesforce / How to use REST API Resources with HTTP callouts

How to use REST API Resources with HTTP callouts

HTTP callout and How to use REST Resources provided by Salesforce

 

To make a HTTP Callout we need to first authorise a user and in this post I will use User-Password Flow of OAuth authentication.

Before we jump in to code, there are couple of prerequisite to start this integration. In this post I am going to connect one salesforce org with another salesforce org.

HTTP Callout and REST Resource

To start our Integration we have to make some point & click configurations in both target and source org.

Configuration at Target Org.

  1. Create a Connected Org (How to make Connected Org click here).
  2. Generate the Consumer Secret and consumer Id from the configuration setting

Configuration at Source Org.

  1. Add two Remote site setting (This will whitelist the URLs at the source org).
    1. One for https://login.salesforce.com
    2. Second for https://<-Yourdomain->.salesforce.com.

After doing the above mentioned configurations we need to understand how the REST callout works in Salesforce.

To make a REST call we need to authenticate the user first, when a user is authorised salesforce returns instance URL and Access Token for the authenticated user. To authorise a user and generate an access token in return we first write a class as shown below.

global class SF2SF_REST_Req {
global Static String oauthLogin(String loginUri, String clientId,
String clientSecret, String username, String password) {
HttpRequest req = new HttpRequest();

req.setMethod(‘POST’);
req.setEndpoint(loginUri+’/services/oauth2/token?grant_type=password’+
‘&client_id=’ + clientId +
‘&client_secret=’ + clientSecret +
‘&username=’ + EncodingUtil.urlEncode(username, ‘UTF-8’) +
‘&password=’ + EncodingUtil.urlEncode(password, ‘UTF-8’)+ ‘SECURITYTOKEN’
);

system.debug(‘req.getBody ‘ + req);

Http http = new Http();

HTTPResponse res = http.send(req);

System.debug(‘BODY: ‘+res.getBody());
System.debug(‘STATUS:’+res.getStatus());
System.debug(‘STATUS_CODE:’+res.getStatusCode());

return res.getBody();
}
}

In the class SF2SF_REST_Req, I have created a method oauthLogin which returns a Static String, this string will contain the information related to the authenticated user.

In oauthLogin method, I take login URL, client Id, client secret, username and password as parameters and make an http request to the user-Password flow API i.e ‘/services/oauth2/token’. If this Http request is successful it returns access token, instance url and other information of the authenticated User and I return the response body as a string from this method.

Now we can use this method anywhere in our org to authenticate Users.

To begin with we create another class where we will make various REST Requests from one Salesforce org to other org.

public class restRequestExample {
public Static String response = ” ;
public Static String oAuthResponse ;
public Static String InstanceURL = ”;
public Static String accessToken = ”;
public static string endPointURL = ”;
public static Map<String, Object> m = new  Map<String, Object> ();
public static void webResponse(){
oAuthResponse = SF2SF_REST_Req.oauthLogin(‘https://login.salesforce.com’,CLIENTID’,CLIENTSecret,USerName’,PassWord);
m = (Map<String, Object>)JSON.deserializeUntyped(oAuthResponse);

InstanceURL = String.valueOf(m.get(‘instance_url’));
accessToken = String.valueOf(m.get(‘access_token’));

system.debug(‘InstanceURL ->’ + InstanceURL + ‘ accessToken -> ‘ + accessToken);
}

}

In the class restRequestExample I have created few strings variable which will hold reponse, oAuthResponse, instance Url, Access Token and End point URL. In the method Web response I make use of the oauthLogin method of SF2SF_REST_Req class. And store its response in oAuthResponse. I next deserialise this response into a map of type <string, Object>. From this map I find the value of instance URL and access token and store them in the respective string variables.

After the above step we now have the instance URL and access token, the two parameter which makes a REST authenticated. To proceed further I again make a method which is used to generate various http Request as per the given requirement. Definition of the method is given below.

public static HttpRequest httpRequestGenerator(String reqMethod, String endpoint, String accessToken, String reqBody){
String authorizationHeader = ‘Bearer ‘ +accessToken;
HttpRequest httpRequest = new HttpRequest();
httpRequest.setMethod(reqMethod);
httpRequest.setEndpoint(endpoint);
httpRequest.setHeader(‘Authorization’, authorizationHeader);
httpRequest.setHeader(‘Content-Type’, ‘application/json;charset=UTF-8’);
httpRequest.setBody(reqBody);
return httpRequest;
}

This method takes reqest method, endpoint URL, access token and request body as String parameters and will return httpRequest as a response. Access token is used to create the value of the authorization header of the http request and request method defines whether the request will be GET, POST, PUT etc. depending upon the Request method we will either have request body or not. Finally we set the endpoint URL from the passed parameter and then returns the created Http request.

Now we will make various REST Callouts from our source org to the target as below

How to get the Org version information Using REST callout.

For this purpose we make use of the below method.

public static void getOrgVersionInfo(String accessToken, string instanceURL ){

endPointURL = instanceURL + ‘/services/data/’;
Http http = new Http();
HttpRequest httpRequest = httpRequestGenerator(‘GET’, endPointURL, accessToken,null);
HTTPResponse httpResponse = http.send(httpRequest);
response = httpResponse.getBody();
system.debug(‘httpResponse.getBody() ->’+httpResponse.getBody());
OVIRW = (list<OrgVersionInfoResponseWrapper>)Json.deserialize(response, list<OrgVersionInfoResponseWrapper>.class);
for(OrgVersionInfoResponseWrapper objWraper : OVIRW){
system.debug(‘Label-> ‘ +objWraper.label);
system.debug(‘url-> ‘ +objWraper.url);
system.debug(‘version-> ‘ +objWraper.version);
}

}

Method getOrgVersionInfo takes two string parameters namely, access token and instance url. With help of the the provided parameter we generate the http request using the httpRequestGenerator method and make a callout.

Once we have made the callout we would get a JSON object as a response of the request. To fetch the desired values from the JSON string we first need to deserialise. To deserialise a String we are supposed to provide it with a blue print, i.e. we need to create a wrapper class. Example of a wrapper response class is given below.

public class OrgVersionInfoResponseWrapper{
String label;
String url;
String version;
}

Response of the http callout in the getOrgVersionInfoversion method is nothing but a list of the OrgVersionInfoResponseWrapper and therefore we deserilise it as a list of the OrgVersionInfoResponseWrapper class, then go through the list and print the desired information.

So this in nut shell how you make a REST callout from one SFDc org to Another SFDC org.

Also, Have a look at the below resources:

  1. Best Salesforce Interview Questions book with Apex and Visualforce concept explained

Also, Have a look at the below learning resources:

  1. SOQL (Salesforce Object Query Language)

  2. Apex Trigger Best Practices and the Trigger Framework

  3. Salesforce Interview Question and Answers Part 2

  4. Salesforce Interview Questions on Test Class

  5. Salesforce-lightning-interview-questions-2018

     6. Salesforce Interview Questions Batch Class 

 

 

 

About Sumit Datta

Sumit Datta
I am a 3x Certified Salesforce developer with overall 5 years of IT experience and 3 years of Implementation experience in Salesforce. I am here to share my knowledge and help Beginners in Salesforce to understand the concepts of Apex, Visualforce, Salesforce Lightning and Salesforce Configuration.

Check Also

MODAL Box

How to create a Modal box in Lightning Component?

How to create a Modal box in Lightning Component? In this post we are going …

Salesforce Lightning Training

How to send parameters in AuraEnabled methods in Salesforce Lightning Components?

How to send parameters in AuraEnabled methods in Salesforce Lightning Components? Passing value to and …

Salesforce Lightning Tutorials

How to use lightning accordion

How to use lightning accordion and how to dynamically add accordion section in lightning. In …

Salesforce Lightning Tutorial

How to fetch and display list of records in Lightning Component

How to fetch and display list of records in Lightning Component? In this post we …

Leave a Reply

Your email address will not be published. Required fields are marked *