Tag Archives: RestAPI

Connecting one Salesforce Org to another via Rest API

I was thinking for long to publish this article. My initial purpose was to learn all major concepts behind Rest API.

Since I don’t have other apps available which I can use for connection so decided that I should Salesforce both as Sending(A) as well as Receiving org(B).

Apart from Rest API basics, This also gave me opportunity to learn following :

  • 1. Expose Apex Classes as REST Resource.
  • 2. JSON serialization and deserialization
  • 3. Making both POST as well as GET request for Rest API call.

We’ll start with ‘RECEIVING ORG CHANGES’

Step 1:  We’ll start with steps needed to configure receiving org(B). Business case : Opportunity is created and closed in ‘Receiving org(B) .After that an order is created outside receiving org. In our case , we ‘ll update Order Amount in  Account object in Receiving org(B) from data created in ‘Sending Org(A).

Step 2: Create a new class in  B . We’ll expose this class as rest resource, so that it can receive data and update Account

@RestResource(urlmapping = '/getAccountData/*')
global  class AccountRestService {
@httpGet
global static string DepositAmountviaGet()
{
integer DepositAmount = Integer.valueOf(RestContext.request.params.get('amount'));
String AccId = RestContext.request.params.get('AccountId');

list acclist = [select id, DevWorld__Deposit_Amount__c, DevWorld__Deposit_Date__c 
from account where id = :Accid];
if(acclist.size()==0)
return 'AccountNotFound';
else
{
try{
account a = acclist[0];//For sake of simplicity, consider handling on record.
a.DevWorld__Deposit_Amount__c = DepositAmount;
update a;

}
catch(exception e)
{
}
return 'Deposit updated succesfully';
}
}

Few points to be noted :

  • Class is declared as Global and method Global & Static
  • You’ve to use annotation   @RestResource with Url mapping as some string like get AccountData before Class declaration.Note the exact syntax. This URL mapping string will be used to create URL for making request from sending ORG.

                 @RestResource(urlmapping = ‘/getAccountData/*’)

  •   Note @httpget  annotation before method-  we’ll be calling this rest resource using ‘GET’ method of http request from API call of Sending org
  • This class will receive two parameters, AccountID, indicating which Account need to be updated and Deposit Amount.

Step 3:   Now since, another SFDC org has to call this rest resource, so we’ve to add ‘Salesforce as ‘connected org’ in this receiving org.

For this  follow below steps

  • Go to Setup | Create | Apps , create new connected App, say with name as ‘SendingSFDCOrg’. 
  • Fill other settings as shown in below screeshot. Important thing is you’ve to provide call back URL and Oauth Scopes.

Connected App

On Saving, you’ll get screen where Client Id and Client Secret will be available to you as shown below:

This client Id and secret will be used in the sending org for authentication.

ClientIdnSecret

Now we’ll move to the Sending Org changes

Step 1:   Create a New VF Page which will show2 fields to enter

AccountID –  User will enter ‘ID’ of some account in receiving org.
Deposit Amount – User will enter Deposit amount to be updated in receiving org.

<apex:page controller="clsSubmitDatainOtherOrg">
<apex:form >
<apex:pageblock >
<apex:pageblockSection >
<apex:inputtext label="Enter Account Id" value="{!AccountId}" />
<apex:inputtext label="Enter Deposit Amount" value="{!depositAmount}" />
</apex:pageblockSection>

<apex:commandButton value="Submit Data" Action="{!SubmitDataUsingGet}"/>
</apex:pageblock>
</apex:form>
</apex:page>

Step 2: Update Controller with following code :

public class clsSubmitDatainOtherOrg {

// we'll be making Oauth Request first to get token,
// One we've token we'll make Rest API call to get data updated in target Org.
public Integer depositAmount{get;set;}
public string AccountId{get;set;}

// This four variables are required for authentication to Oauth Token
String clientId = 'Your Client Id copied from Receiving Org' ;
String clientSecret = 'Your client Secret copied from Receiving Org';
String username= 'Your User Id';
String password= 'your Pwd';

//This method is called form VF page on Submit
public PageReference SubmitDataUsingGet() {

//using this request body we'll make API call
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='
+clientSecret+'&username='+username+'&password='+password;

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
//Note if my domain is set,use the proper domain name else use login.salesforce.com
// for prod or developer environment, and test.salesforce.com for sandbox

HttpResponse res = h.send(req);
OAuth2 objAuthenticationInfo =(OAuth2)JSON.deserialize(res.getbody(), OAuth2.class);

// proceed further only if you get token
if(objAuthenticationInfo.access_token!=null){

// First create http and req object and set EndPoint
// Note Endpt, this part is common' https://ap1.salesforce.com/services/apexrest/
//'getAccountData' name is URLMapping you set while creating Rest 
//resource in Receiving org.

Http h1 = new Http();
HttpRequest req1 = new HttpRequest();
string EndPt = 'https://ap1.salesforce.com/services/apexrest/getAccountData?' +
'AccountId='+AccountId+'&amount='+depositAmount ;

// Set request header to send token, setMethod, and set Endpoint
req1.setHeader('Authorization','Bearer '+objAuthenticationInfo.access_token);
req1.setMethod('GET');
req1.setEndpoint(EndPt);


//finally make a call
HttpResponse res1 = h1.send(req1);
system.debug('RESPONSE_BODY'+res1 .getbody());
}
return null;
}
}

If you’ve set everything correctly,  data will be updated in the target org.

We” learn how to connect using post method in next post