HTTP callout to create a new record in Salesforce

HTTP callout to create a new record in Salesforce

HTTP callout to create a new record in 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 create a new record in 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 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′,’[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;
}

//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

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.