Thursday, 26 November 2015

Salesforce to Salesforce Integration Using REST API and OAuth

Lets Start with Salesforce to Salesforce Integration Using REST API and OAuth.
Here I wanted to Access the All contacts for an Account From Target Org(2nd Salesforce Org)


In Source Org Create one Connected App:

Login into Salesforce Sandbox or Salesforce Developer Org
then goto Setup-> App->Connected App
Click New

Change the Oauth CallBack URL according to your instance. Here my instance is "CS30"

Then Save it.

After Save you will get Consumer Key & Consumer Secret

After this now we have to Develop one Apex RestService in the Same Source Org.

Step 2: Click on Setup-> Develop->Apex Class
Click New and Save it.
The purpose of this method is to return all contacts related to AccountId

  1. @RestResource(urlMapping='/v1/getContacts/*')
  2.    global with sharing class getContact {
  3.      @Httpget
  4.       global static list<contact> fetchAccount(){
  5.         RestRequest req = RestContext.request;
  6.         RestResponse res = Restcontext.response;
  7.         Id accId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
  8.         list<contact> lstcontact =[Select id , name,Phone,Fax,Email from contact where Accountid=:accId ];
  10.         return lstcontact ;
  11.       }
  12.    }
Step-3: Now we have to consume the above Apex Rest Service in Target Salesforce Org.
  1. Login into Target Org
  2. Create new Apex Class "SendAccountUsingRESTAPI " see below
Replace following 4 values in your Apex Class
  • clientId 
  • clientSecret 
  • username 
  • password 
Also Change the Endpoint(line no.18) in which org you are trying to login. means where you have create your Connected App


Also Change the Endpoint(line no.32) in which org you are trying to access all the Contacts. means where you have developed your Apex RestService

String endPoint = '' +accId;

public class SendAccountUsingRESTAPI {
  private final String clientId = 'XXXX1qDQKpai6KLQyEHS3pvpCcteS2b5rWP2A6JpuqP._w2byvgpP8EC56LtyVNOg7.p7';
   private final String clientSecret = '17825308XXX';
   private final String username = '';
   private final String password = 'XXX';
  public class deserializeResponse
      public String id;
      public String access_token;
  public String ReturnAccessToken (SendAccountUsingRESTAPI acount)
      String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
     Http h = new Http();
      HttpRequest req = new HttpRequest();
      HttpResponse res = h.send(req);
     deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
     system.debug('@@@@access_token@@'+resp1 );
      return resp1.access_token;
   public static list<Contact> callgetContact (String accId)
           SendAccountUsingRESTAPI acount1 = new SendAccountUsingRESTAPI();
           String accessToken;
           accessToken = acount1.ReturnAccessToken (acount1);
           list<Contact> LstContact=new List<Contact>();
           if(accessToken != null){
           String endPoint = '' +accId;
           //String jsonstr = '{"accId" : "' + accId+ '"}';
           Http h2 = new Http();
           HttpRequest req1 = new HttpRequest();
           req1.setHeader('Authorization','Bearer ' + accessToken);
           HttpResponse res1 = h2.send(req1);
           String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
           JSONParser parser = JSON.createParser(res1.getBody());
           set<Contact> contList=new set<Contact>();
            while (parser.nextToken() != null) {
                if((parser.getCurrentToken() == JSONToken.FIELD_NAME) ){
                    Contact cont;
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) {
                    // Get the value.
                    // Compute the grand total price for all invoices.
                    string sId= parser.getText();
                    cont=new Contact();
                    system.debug('Id@@@' + sId);
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                        (parser.getText() == 'Name')) {
                        // Get the value.
                        // Compute the grand total price for all invoices.
                        string sName= parser.getText();
                        system.debug('Name@@@' + sName );
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                        (parser.getText() == 'Email')) {
                        // Get the value.
                        // Compute the grand total price for all invoices.
                        string sEmail= parser.getText();
                        system.debug('Email@@@' + sEmail);
        return LstContact;


Yes now we are ALL set, you can call this  "callgetContact " in your visualforce Controller Class or in your Apex Trigger wherever you wanted to Show the List of Contacts..from Source Org.

Access List of Contact Using Following Syntax


Need help, please call me +91-95823-88885 or email me


  1. Its really good steps to Salesforce to Salesforce Integration Using REST API and OAuth .

  2. Owesome solution with step by step description.

  3. if i want to integration with legacy systm then.....

  4. can u explain integretion with legacy system any one

    1. what legacy system you have. we can integrate with java, .net

  5. I hope this is the custom REST api, correct me if I'm wrong

  6. hi salesfroce 2 salesfroce integration is paossibke by using REST API. same as one salesforce Organization data integrate with Other Organization not salesforce is it possible.
    if Possible how to do.....

    1. I did get your point. If Data Transfer you are looking from org to another Org. use ETL tool or Dataloader CLI.

  7. Thanks for sharing the informative post on salesforce integration.

    Salesforce Integration Services

  8. This comment has been removed by a blog administrator.

  9. Can you please share the visual force code too. thanks

  10. thanks for your information excelllent blog good support for salesforce
    sales force mostly important topices

  11. When we login with user name and password, salesforce also provides a security token string that must be appended to the password. How is that handled here? Should we hardcode that security token in the code? when the password/token changes for the integrated user, the code must be changed??

  12. Hi,
    I am trying to learn integration using the code you provided. However when I try to display contact information from source org in my destination org(using vf page) I get the error :
    Status Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null') at input location [1,2]

    02:06:53.0 (8960006)|CALLOUT_REQUEST|[19]|System.HttpRequest[Endpoint=, Method=POST]
    02:06:53.0 (69643751)|CALLOUT_RESPONSE|[19]|System.HttpResponse[Status=Not Found, StatusCode=404]

    I think it means my endpoint url is wrong but I did how it was asked and still doesn't work.Here's my endpoint url:

    Can you kindly tell me what is wrong in it or what I am missing.

  13. I acknowledge the author for his brilliant work for making this exceptionally useful and informative content to guide us.
    salesforce integration

  14. Very good and easy understanding, Why cant you add a VF page code as well where all contacts are organized in pageblocktable.

  15. can you please provide the trigger code for callout

  16. Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
    Salesforce Services
    Keep Posting:)

  17. For every request, it'll take 2 api calls. 1- get access_token and 2 - get contact. Can we store the access_token in somewhere, check the token valid. if not, we'll refresh the token, if token still valid, we can continue use it.

  18. So nice to read.Its very useful for me to get more valuable info about Medical Billing Coding Service.Thanks for it.Keep going.
    html training in chennai |
    html5 training in chennai |
    html5 courses in chennai

  19. Most of the healthcare institutes are procuring the software packages for their coding and billing process from medical
    Salesforce Training in Chennai |
    Salesforce Training |
    Salesforce Training Institutes in Chennai

  20. how do i create an email escaltion from one URL of salesforce to another ?

  21. Hi, I am trying perform the same as per this post, and my code is also similar except the Parser Instance. But I am getting an error when I tried to run the class through Anonymous window. The error is "System.HttpResponse[Status=Bad Request, StatusCode=400]". Any help would be highly appreciated. Thanks!

  22. Thank you for sharing such great information very useful to us.
    Salesforce Training in Gurgaon

  23. Really nice post, Thanks for sharing such an informative post.
    To Create Bulk Fields in Salesforce click this links

  24. I really enjoyed while reading your article and it is good to know the latest updates. Do post more. Please also read my topics about

    Salesforce Products
    Salesforce Consultant
    Salesforce Integration Service

  25. ExpressTech Software Solutions is known as best custom Rest API Integration Services in India, USA, has the best in the industry specialization to deliver seamless API integration and development services. Our system integration services make sure that your web application or website is without flawlessly integrated with the standard or custom APIs.


lightning:pillContainer and dialog(openModel or openPopup)

lightning:pillContainer and dialog(openModel or openPopup) AddAttendees.cmp <aura:component controller="AddAttendeesCo...