The post How to use Custom setting in Salesforce? appeared first on Salesforce Next Gen.
]]>In this post we are going to discuss how to create a custom setting and how to use the Custom setting API.
To know more about the custom setting kindly go through the post here.
To create a Custom setting follow the below steps:-
Once you have created all the required fields the custom setting detail page looks something as below.
Once you have completed creating the custom setting, then it is the time to enter some data in the custom setting datasets. To insert the data we need to click on the manage button on the custom setting detail page, as shown below.
Clicking on the manage button, redirects to the dataset detail page where we can add. Delete and edit records of custom settings.
On this page, to create a new record click on the new button and enter the value in the fields and click on save as shown below.
Once you have desired number of records I the custom setting. We can use the Custom setting API’s to fetch the records.
Below I have written a class which access the custom settings without making a SOQL call to database and returns a map of string and custom setting records.
public class CustomSettingCls {
public map<String, IVL_Offline_document__c> fetchDocMapFromCustomSetting(String profileName){
map<String, IVL_Offline_document__c> mcs = new map<String, IVL_Offline_document__c>();
list<IVL_Offline_document__c> lcs = IVL_Offline_document__c.getall().values();
for(IVL_Offline_document__c recordCS : lcs){
if(recordCS.IVL_Profile_Name__c == profileName){
mcs.put(recordCS.Name, recordCS);
}
}
return mcs;
}
}
7. Custom Setting in Salesforce
The post How to use Custom setting in Salesforce? appeared first on Salesforce Next Gen.
]]>The post HTTP callout to fetch query result from Salesforce appeared first on Salesforce Next Gen.
]]>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.
To start our Integration we have to make some point & click configurations in both target and source org.
Configuration at Target Org.
Configuration at Source Org.
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′,’datta.sumit.1987@gmail.com’,’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.
The post HTTP callout to fetch query result from Salesforce appeared first on Salesforce Next Gen.
]]>The post HTTP callout to Delete a record in Salesforce appeared first on Salesforce Next Gen.
]]>
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.
To start our Integration we have to make some point & click configurations in both target and source org.
Configuration at Target Org.
Configuration at Source Org.
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 Delete a record using Http Callout?
To Delete a record we first need to make a POST request, in this POST request we will supply the value of fields of a Sobject we need to update, in the request body of the http callout, in JSON format. There is no Response from the server when a record is updated at Salesforce.
The endpoint to delete an account is as shown below:
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/Account/001D000000INjVe
More generalised syntax would be
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/sObjectName//<–Record ID à
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′,’datta.sumit.1987@gmail.com’,’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;
}
// Delete an Account record
public static void deleteAccount(String accessToken, string instanceURL ){
endPointURL = instanceURL + ‘/services/data/v20.0/sobjects/Account/0012800000nfnDXAAY’;
Http http = new Http();
HttpRequest httpRequest = httpRequestGenerator(‘POST’, endPointURL, accessToken, null);
HTTPResponse httpResponse = http.send(httpRequest);
system.debug(‘httpResponse -> ‘+ httpResponse);
system.debug(‘httpResponse.getHeaderKeys() -> ‘+ httpResponse.getHeaderKeys());
}
Method webResponse and httpRequestGenerator has been previously explained here. To create an account record, I have used the method createAccount. It takes access token and instance url as the parameters. We create a Http request for this method using httpRequestGenerator method and provided the parameter as following, Request Method: POST, endpoint URL of creating a sObject record, access token and the requestBody which provided the required fields necessary to update the sObject.
This is how you delete a record of Sobject using REST endpoint provided by Salesforce
The post HTTP callout to Delete a record in Salesforce appeared first on Salesforce Next Gen.
]]>The post HTTP callout to Update a record in Salesforce appeared first on Salesforce Next Gen.
]]>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.
To start our Integration we have to make some point & click configurations in both target and source org.
Configuration at Target Org.
Configuration at Source Org.
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 Update a record using Http Callout?
To Update a record we first need to make a POST request, in this POST request we will supply the value of fields of a Sobject we need to update, in the request body of the http callout, in JSON format. There is no Response from the server when a record is updated at Salesforce.
The endpoint to update an account is as shown below:
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/Account/001D000000INjVe
More generalised syntax would be
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/sObjectName//<–Record ID à
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′,’datta.sumit.1987@gmail.com’,’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;
}
// update Field on Account — PATCH Method is used
public static void updateFieldOnAccount(String accessToken, string instanceURL ){
endPointURL = instanceURL + ‘/services/data/v20.0/sobjects/Account/0012800000nfnDXAAY’;
Http http = new Http();
HttpRequest httpRequest = httpRequestGenerator(‘PUT’, endPointURL, accessToken, null);
HTTPResponse httpResponse = http.send(httpRequest);
system.debug(‘httpResponse -> ‘+ httpResponse);
system.debug(‘httpResponse.getHeaderKeys() -> ‘+ httpResponse.getHeaderKeys());
}
Method webResponse and httpRequestGenerator has been previously explained here. To create an account record, I have used the method createAccount. It takes access token and instance url as the parameters. We create a Http request for this method using httpRequestGenerator method and provided the parameter as following, Request Method: PUT, endpoint URL of creating a sObject record, access token and the requestBody which provided the required fields necessary to update the sObject.
This is how you update a field on a record of Sobject using REST endpoint provided by Salesforce
The post HTTP callout to Update a record in Salesforce appeared first on Salesforce Next Gen.
]]>The post HTTP callout to create a new record in Salesforce appeared first on Salesforce Next Gen.
]]>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.
To start our Integration we have to make some point & click configurations in both target and source org.
Configuration at Target Org.
Configuration at Source Org.
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 create a record using Http Callout?
To create a record we first need to make a POST request, in this POST request we will supply the basic information/required fields of a Sobject in the request body in JSON format. Response of this POST request is a record ID of the newly created record.
The endpoint to create an account is as shown below:
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/Account/
More generalised syntax would be
https://<—yourInstance—>.salesforce.com/services/data/vXX.X/sobjects/sObjectName/
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′,’datta.sumit.1987@gmail.com’,’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;
}
//Create an account Record
public static void createAccount(String accessToken, string instanceURL){
endPointURL = instanceURL + ‘/services/data/v20.0/sobjects/Account/’;
Http http = new Http();
//String RequestBody = JSON.serialize(‘{“Name”:”Account Created Using REST”}’);
String RequestBody = ‘{“Name”:”AccountCreated Using REST”}’;
system.debug(‘RequestBody -> ‘ + RequestBody);
HttpRequest httpRequest = httpRequestGenerator(‘POST’, endPointURL, accessToken,RequestBody);
HTTPResponse httpResponse = http.send(httpRequest);
system.debug(‘httpResponse -> ‘+ httpResponse);
}
}
Method webResponse and httpRequestGenerator has been previously explained here. To create an account record, I have used the method createAccount. It takes access token and instance url as the parameters. We create a Http request for this method using httpRequestGenerator method and provided the parameter as following, Request Method: POST, endpoint URL of creating a sObject record, access token and the requestBody which provided the required fields necessary for creation of the sObject.
Sample response received is as shown below:
{
“id” : “001D000000IqhSLIAZ”,
“errors” : [ ],
“success” : true
}
This is how you create a record of Sobject using REST endpoint provided by Salesforce
The post HTTP callout to create a new record in Salesforce appeared first on Salesforce Next Gen.
]]>The post How to use REST API Resources with HTTP callouts appeared first on Salesforce Next Gen.
]]>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.
To start our Integration we have to make some point & click configurations in both target and source org.
Configuration at Target Org.
Configuration at Source Org.
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.
The post How to use REST API Resources with HTTP callouts appeared first on Salesforce Next Gen.
]]>The post How to Authenticate user using Username-Password Authentication Flow in Salesforce? appeared first on Salesforce Next Gen.
]]>Salesforce uses oAuth protocol to allow application users to access the data in salesforce securely without exposing Username and password of a particular user.
But before we could make a REST Api call, we need to authenticate our app with salesforce, by making it a connected app. To make an App as connected app follow the steps given in this post.
There are several OAuth endpoints provided by Salesforce, depending upon our requirement and resources we need to choose an authentication flow from the below
Once we have successfully authenticated our connected app user, salesforce provide us with an access token, which are further utilised to make authenticated REST Api calls.
In this post we are going to discuss the Username-Password Authentication Flow.
This authentication flow make use of user’s credentials directly on the web server and should be used only if necessary, there is no refresh token is provided in this flow, see the flow diagram below.
Step wise breakdown of the authentication flow:
Parameter Description
grant_type Must be password for this authentication flow.
client_id The Consumer Key from the connected app definition.
client_secret The Consumer Secret from the connected app definition. Required unless the Require Secret for Web Server Flow setting is not enabled in the connected app definition.
username End-user’s username.
password End-user’s password.
Example authorization url will look something like this:
grant_type=password&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret=1955279925675241571&username=testuser%40salesforce.com&password=mypassword123456
Parameters Description
access_token Access token that acts as a session ID that the application uses for making requests. This token should be protected as though it were user credentials.
instance_url Identifies the Salesforce instance to which API calls should be sent.
id Identity URL that can be used to both identify the user as well as query for more information about the user. Can be used in an HTTP request to get more information about the end user.
issued_at When the signature was created, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970).
signature Base64-encoded HMAC-SHA256 signature signed with the consumer’s private key containing the concatenated ID and issued_at value. The signature can be used to verify that the identity URL wasn’t modified because it was sent by the server.
An example of the response is as shown below
{“id”:”https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P”,
“issued_at”:”1278448832702″,”instance_url”:”https://***yourInstance***.salesforce.com/”,
“signature”:”0CmxinZir53Yex7nE0TD+zMpvIWYGb/bdJh6XfOH6EQ=”,”access_token”:
“00Dx0000000BV7z!AR8AQAxo9UfVkh8AlV0Gomt9Czx9LjHnSSpwBMmbRcgKFmxOtvxjTrKW1
9ye6PE3Ds1eQz3z8jr3W7_VbWmEu4Q8TVGSTHxs”}
The post How to Authenticate user using Username-Password Authentication Flow in Salesforce? appeared first on Salesforce Next Gen.
]]>The post How to Authenticate user in Salesforce? appeared first on Salesforce Next Gen.
]]>Salesforce uses oAuth protocol to allow application users to access the data in salesforce securely without exposing Username and password of a particular user.
But before we could make a REST Api call, we need to authenticate our app with salesforce, by making it a connected app. To make an App as connected app follow the steps given in this post.
There are several OAuth endpoints provided by Salesforce, depending upon our requirement and resources we need to choose an authentication flow from the below
Once we have successfully authenticated our connected app user, salesforce provide us with an access token, which are further utilised to make authenticated REST Api calls.
In this post we are going to discuss the User-Agent Authentication Flow.
This authentication flow is used by the application which are hosted over a secure server. In this flow client application redirects the user to another web server i.e. an authorization server where the user get generates an authorize code, now this authorise code is used to fetch the access token from the Salesforce, see the flow diagram below.
Step wise breakdown of the authentication flow:
Parameter Description
response_type Must be token for this authentication flow.
client_id The Consumer Key from the connected app definition.
redirect_uri The Callback URL from the connected app definition.
Example authorization url will look something like this:
https://login.salesforce.com/services/oauth2/authorize?response_type=token
&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3X
HrXDiCQjK1mdgAvhCscA9GE&redirect_uri=https%3A%2F%2Fwww.mysite.com%2F
code_callback.jsp&state=mystate
Parameters Description
access_token Access token that acts as a session ID that the application uses for making requests. This token should be protected as though it were user credentials.
expires_in Amount of time the access token is valid, in seconds.
refresh_token Token that can be used in the future to obtain new access tokens.
Warning
The refresh token is only returned if the redirect URI is https://login.salesforce.com/services/oauth2/success or used with a custom protocol that is not HTTPS.
state The state value that was passed in as part of the initial request, if applicable.
instance_url Identifies the Salesforce instance to which API calls should be sent.
id Identity URL that can be used to both identify the user as well as query for more information about the user. Can be used in an HTTP request to get more information about the end user.
issued_at When the signature was created, represented as the number of seconds since the Unix epoch (00:00:00 UTC on 1 January 1970).
signature Base64-encoded HMAC-SHA256 signature signed with the consumer’s private key containing the concatenated ID and issued_at value. The signature can be used to verify that the identity URL wasn’t modified because it was sent by the server.
E.g.
https://www.mysite.com/user_callback.jsp#access_token=00Dx0000000BV7z%21AR8
AQBM8J_xr9kLqmZIRyQxZgLcM4HVi41aGtW0qW3JCzf5xdTGGGSoVim8FfJkZEqxbjaFbberKGk8v8AnYrvChG4qJbQo8&refresh_token=5Aep8614iLM.Dq661ePDmPEgaAW9Oh_L3JKkDpB4xReb54_pZfVti1dPEk8aimw4Hr9ne7VXXVSIQ%3D%3D&expires_in=7200&state=mystate
Keep following point in mind when using User Agent flow. The encoded access token resides in redirect URL and is therefore exposed to the applications installed at end-user system. If javascript was used to retrieve the access token, then use window.location.replace() to remove callback from the browser’s history.
Further we will discuss about the other two authentication flow.
The post How to Authenticate user in Salesforce? appeared first on Salesforce Next Gen.
]]>The post How to make HTTP Callouts in salesforce and how to test HTTP Callouts? appeared first on Salesforce Next Gen.
]]>Salesforce has created three classes to perfom HTTP Callouts namely, Http, HttpRequest, HttpResponse classes.
Http: to initiate the Request and response of, HttpRequest class creates a request object for methods like GET,POST etc and HttpResponse class creates a response object returned from the callout.
Before making Http callout we need to understand that, the response of web callout from the system is dependent on the external web server is therefore advised that web callout should be performed asynchronously, i.e. use @future Annotation, otherwise no further processing before we receive a response.
In below example we will make a GET Http Request to an external web server
Public class HTTPExample {
Public String getHttpResponseFromWebServer(string url){
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(url);
req.setMethod(‘GET’);
HttpResponse res = http.send(req);
Return res.getBody();
}
}
This is a very basic example of making Http Callout.
Creating Http Callout is easy task, but to deploy code to production we need to cover 75% of the code lines. But test method do not support Http Callouts, then how do we test a class making Http Callout. To overcome this Salesforce has provided with a trick where we provide the test class with a mock response and we use these response to verify the callout class.
To create a class which generates a mock Http callout reponse has to implement HttpCalloutMock Interface. E.g.
Global class mockClassName implements HttpCallMock{
Global HTTPResponse respond(HttpRequest req){
//Write your logic here to create a mock / fake response
}
}
Once we have created our mock callout class we need to call it during the execution of test class. For this we have to call a method Test.setMock and its syntax is as following.
Test.setMock(HttpCalloutMock.class, new mockClassName ());
After this method is called in test class, if an Http request is invoked then no callout is made but the response generated from your mock class’s method is used
Below is a full example of Http callout and how to test it.
@isTest
global class yourMockHttpResponseGeneratorClass implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
System.assertEquals(‘http://abc.com/abc’, req.getEndpoint());
System.assertEquals(‘GET’, req.getMethod());
HttpResponse res = new HttpResponse();
res.setHeader(‘Content-Type’, ‘application/json’);
res.setBody(‘{“example”:”test”}’);
res.setStatusCode(200);
return res;
}
}
public class YouClassToCallout {
public static HttpResponse getInfoFromWebService() {
HttpRequest req = new HttpRequest();
req.setEndpoint(‘http://abc.com/abc’);
req.setMethod(‘GET’);
Http http = new Http();
HttpResponse res = http.send(req);
return res;
}
}
@isTest
private class YouClassToCalloutTest {
@isTest static void testingTheCallout() {
// Set your mock response callout class here
Test.setMock(HttpCalloutMock.class, new yourMockHttpResponseGeneratorClass ());
HttpResponse res = YouClassToCallout.getInfoFromWebService ();
// you can Verify the fake response received
String contentType = res.getHeader(‘Content-Type’);
System.assert(contentType == ‘application/json’);
String actualValue = res.getBody();
String expectedValue = ‘{“example”:”test”}’;
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}
This is how you make a Http Callout and test it to deploy to production.
The post How to make HTTP Callouts in salesforce and how to test HTTP Callouts? appeared first on Salesforce Next Gen.
]]>The post How to Authenticate user in Salesforce Using REST Api? appeared first on Salesforce Next Gen.
]]>Salesforce uses oAuth protocol to allow application users to access the data in salesforce securely without exposing Username and password of a particular user.
But before we could make a REST Api call, we need to authenticate our app with salesforce, by making it a connected app. To make an App as connected app follow the steps given in this post.
There are several OAuth endpoints provided by Salesforce, depending upon our requirement and resources we need to choose an authentication flow from the below
Once we have successfully authenticated our connected app user, salesforce provide us with an access token, which are further utilised to make authenticated REST Api calls.
In this post we are going to discuss the Web Server Authentication Flow.
This authentication flow is used by the application which are hosted over a secure server. In this flow client application redirects the user to another web server i.e. an authorization server where the user get generates an authorize code, now this authorise code is used to fetch the access token from the Salesforce, see the flow diagram below.
Step wise breakdown of the authentication flow:
Parameter Description
response_type Must be code for this authentication flow.
client_id The Consumer Key from the connected app definition.
redirect_uri The Callback URL from the connected app definition.
Example authorization url will look something like this:
https://login.salesforce.com/services/oauth2/authorize?response_type=code
&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3X
HrXDiCQjK1mdgAvhCscA9GE&redirect_uri=https%3A%2F%2Fwww.mysite.com%2F
code_callback.jsp&state=mystate
Parameters Description
code Authorization code the consumer must use to obtain the access and refresh tokens.
state The state value that was passed in as part of the initial request, if applicable.
E.g.
https://www.mysite.com/authcode_callback?code=aWekysIEeqM9PiT
hEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D
End point: https://login.salesforce.com/services/oauth2/token
Parameter Description
grant_type Value must be authorization_code for this flow.
client_secret The Consumer Secret from the connected app definition.
client_id The Consumer Key from the connected app definition.
redirect_uri The Callback URL from the connected app definition.
code Authorization code the consumer must use to obtain the access and refresh tokens
E.g.
POST /services/oauth2/token HTTP/1.1
Host: login.salesforce.com
grant_type=authorization_code&code=aPrxsmIEeqM9PiQroGEWx1UiMQd95_5JUZ
VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%3D%3D&client_id=3MVG9lKcPoNI
NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCs
cA9GE&client_secret=1955279925675241571&
redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp
Parameters Description
access_token Access token that acts as a session ID that the application uses for making requests. This token should be protected as though it were user credentials.
refresh_token Token that can be used in the future to obtain new access tokens.
instance_url Identifies the Salesforce instance to which API calls should be sent.
id Identity URL that can be used to both identify the user as well as query for more information about the user. Can be used in an HTTP request to get more information about the end user.
E.g. of the Raw JSON response
{“id”:”https://login.salesforce.com/id/00Dx0000000BV7z/005x00000012Q9P”,
“issued_at”:”1278448101416″,
“refresh_token”:”5Aep8614iLM.Dq661ePDmPEgaAW9Oh_L3JKkDpB4xReb54_
pZebnUG0h6Sb4KUVDpNtWEofWM39yg==”,
“instance_url”:”https://***yourInstance***.salesforce.com/”,
“signature”:”CMJ4l+CCaPQiKjoOEwEig9H4wqhpuLSk4J2urAe+fVg=”,
“access_token”:”00Dx0000000BV7z!AR8AQP0jITN80ESEsj5EbaZTFG0R
NBaT1cyWk7TrqoDjoNIWQ2ME_sTZzBjfmOE6zMHq6y8PIW4eWze9JksNEkWUl.Cju7m4″}
This is the web server Authentication Flow used by Salesforce
Further we will discuss about the other two authentication flow.
The post How to Authenticate user in Salesforce Using REST Api? appeared first on Salesforce Next Gen.
]]>