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.
]]>