HTTP callout to fetch query result from Salesforce

HTTP callout to fetch query result from Salesforce

HTTP callout to fetch query result from 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 to fetch query result from Salesforce

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 in this post.

CLick here to understand how to authenticate user before making a REST API Request

Use the class SF2SF_REST_Req created in the link shown above, it contains 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.

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

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 fetch result of a query using Http Callout?

To fetch result of a query from salesforce, we need to make a GET request. This request will have the end point as /query/?q=’Your query’. There is no request body attached with this request and returns a response, for which we need to create a response wrapper so that we can deserialise the JSON Data returned by the executed query.

The endpoint to Execute a SOQL Query is as shown below:

https://<—yourInstance—>.salesforce.com/services/data/ vXX.X /query/?q=SELECT+name+from+Account

here vXX.X -> is the org version of the rest resource.

To make this Http callout I have made the below method in the restRequestExample class.

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’,’3MVG9ZL0ppGP5UrBAQBWYrUKa05u7fcH86snlLCU5mp4.DRt7PrhqrcgCoy2aPdGbFmgCTmZWgtExD__dS88o’,’1267455198314456981′,’[email protected]’,’pepsico@123′);
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);
}

// Method to generate Http Request

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;
}

// Fetch Query result
public static void getQueryResult(String accessToken, string instanceURL ){
endPointURL = instanceURL + ‘/services/data/v41.0/query?q=SELECT+name+from+Account’;
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());
QRRW = (queryReturnResponseWrapper)Json.deserialize(response, queryReturnResponseWrapper.class);
System.debug(‘QRRW.records[0].Name -> ‘+QRRW.records[0].Name);
System.debug(‘QRRW.totalSize -> ‘+QRRW.totalSize);
System.debug(‘QRRW.records[0].attributes.url -> ‘+QRRW.records[0].attributes.url);

}

Method webResponse and httpRequestGenerator has been previously explained here. To create an account record, I have used the method getQueryResult. It takes access token and instance url as the parameters. We create an Http request for this method using httpRequestGenerator method and provided the parameter as following, Request Method: GET, endpoint URL of creating a sObject record, access token and the requestBody which is null in this case.

After the successful execution of the Query, we receive the response in its raw JSON form as shown below.

{

“done” : true,

“totalSize” : 14,

“records” :

[

{

“attributes” :

{

“type” : “Account”,

“url” : “/services/data/v20.0/sobjects/Account/001D000000IRFmaIAH”

},

“Name” : “Test 1”

},

{

“attributes” :

{

“type” : “Account”,

“url” : “/services/data/v20.0/sobjects/Account/001D000000IomazIAB”

},

“Name” : “Test 2”

},

]

}

To de-serialize this response we need to create  a custom wrapper which will provide our class with a blueprint of the expected response and would be able to parse the response JSON String. The wrapper classes to De serialize the response is shown below.

public class attributesWrapper {
string type;
string url;
}

public class recordWrapper {
attributesWrapper attributes;
String Name;
String Id;
public recordWrapper (){
attributes = new attributesWrapper();
}
}

public class queryReturnResponseWrapper{
String done;
String totalSize;
list<recordWrapper> records ;
}

We use this line in the code to de-serialize the response

QRRW = (queryReturnResponseWrapper)Json.deserialize(response, queryReturnResponseWrapper.class);

And then we fetch any required value from this de-serialised response as shown below:

System.debug(‘QRRW.records[0].Name -> ‘+QRRW.records[0].Name);
System.debug(‘QRRW.totalSize -> ‘+QRRW.totalSize);
System.debug(‘QRRW.records[0].attributes.url -> ‘+QRRW.records[0].attributes.url);
So this how you fetch result of an executed SOQL Query at Salesforce using HTTP Callout.

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 

Sumit Datta

Sumit Datta

I am a 5x Certified Salesforce developer with overall 7 years of IT experience and 5 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.

Leave a Comment

Your email address will not be published.