Getting record from other Salesforce organization OR communication between multiple salesforce organization

Calling Rest Web service using Apex – Getting record from other Salesforce organization or Account or communication between multiple salesforce organization

In this article, I will explain the code which can be used for connecting and getting the records from different or multiple salesforce organization using Apex and REST Service.

Note : Here is new article to connect two salesforce instances in just 5 lines of code using Named Credentials.

To start first we will need to authorize below two URL which can be accessed from salesforce environment.
This can be done from “Setup | Administration Setup | Security Controls | Remote Site Settings”

  1. https://www.salesforce.com
  2. https://ap1-api.salesforce.com
Salesforce Remote Site Setting
Salesforce Remote Site Setting


It is possible that you may need to change first URL it may be https://www.na1-api.salesforce.com or https://www.na2-api.salesforce.com

This application will prompt for the Username and Password of the other salesforce account and display the 10 records of the Account.

Connect Other Salesforce Account - Output Screen
Connect Other Salesforce Account – Output Screen

Apex Code:

public with sharing class FetchAccount {

    //Login Domain May be test, prerellogin.pre
    String LOGIN_DOMAIN = 'www';
    public String pwd{get;set;}
    public String userName{get;set;}
    public List<Account> acc{get;set;}
    public String errMsg{get;set;}
    public String displayError{get;set;}

    public FetchAccount()
    {
        displayError = 'none';
    }

    public void fetch()
    {
        errMsg  = 'Some error occurred, please try again';
        try
        {
        //-----------------------------------
        // Login via SOAP/XML web service api
        //-----------------------------------
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
        request.setHeader('SOAPAction', '""');
        //not escaping username and password because we're setting those variables above
        //in other words, this line "trusts" the lines above
        //if username and password were sourced elsewhere, they'd need to be escaped below
        request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
        Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
          .getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
          .getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
          .getChildElement('result', 'urn:partner.soap.sforce.com');

        //-------------------------------
        // Grab session id and server url
        //--------------------------------
        final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
        final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();

        //----------------------------------
        // Load first 10 accounts via REST API
        //---------------------------------
        final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
        theUrl.getParameters().put('q','Select a.Phone, a.Name, a.CreatedBy.FirstName, a.CreatedById From Account a limit 10');
        request = new HttpRequest();
        request.setEndpoint(theUrl.getUrl());
        request.setMethod('GET');
        request.setHeader('Authorization', 'OAuth ' + SESSION_ID);

        String body = (new Http()).send(request).getBody();

        JSONParser parser = JSON.createParser(body);

        do{
            parser.nextToken();
        }while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));

        parser.nextToken();

        acc = (List<Account>) parser.readValueAs(List<Account>.class);
        }
        catch(Exception e)
        {
            displayError = 'block';
        }

    }
}

Visualforce Code:

<apex:page controller="FetchAccount" standardStylesheets="true">
<style type="text/css">
.errorMsg{
    font-size:0.8 em;
    color:red;
}
</style>
<apex:pageBlock >
<apex:form >
<apex:outputLabel value="UserName : " for="userName"/>
<apex:inputText required="true" id="userName" value="{!userName}" />
<br />
<apex:outputLabel value="Password : " for="pwd"/>
<apex:inputsecret id="pwd" value="{!pwd}"/>
<br />
<apex:commandButton id="getRecords" value="Get Records" action="{!fetch}" rerender="wrapper" status="waitStatus" />
<apex:actionStatus startText="Requesting..." stopText="" id="waitStatus"/>
<hr />
<apex:outputPanel id="wrapper">
<div class="errorMsg" style="display:{!displayError}"> {!errMsg} </div>
<apex:pageBlockTable value="{!acc}" var="account" id="accTable" rowClasses="odd,even" styleClass="tableClass">

    <apex:column >
        <apex:facet name="header">Account Name</apex:facet>
         <apex:outputText value="{!account.name}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Created By</apex:facet>
         <apex:outputText value="{!account.CreatedBy.FirstName}"/>
    </apex:column>

    <apex:column >
        <apex:facet name="header">Phone</apex:facet>
         <apex:outputText value="{!account.Phone}"/>
    </apex:column>

</apex:pageBlockTable>
</apex:outputPanel>
</apex:form>
</apex:pageBlock>
</apex:page>

Related posts

63 thoughts on “Getting record from other Salesforce organization OR communication between multiple salesforce organization”

  1. Hi ,
     
    I was trying this example in my personal environment , but i am getting below exception
     
    16:45:22:037 EXCEPTION_THROWN [23]|System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://www.salesforce.com/services/Soap/u/22.0
     
    In Remote settings  under site url ” https://www.na14-api.salesforce.com” for salesforce login
    and for api https://ap14-api.salesforce.com  or https://ap1-api.salesforce.com also tryed both.

    could you please tell me why i am getting unauthorized endpoint.

      1. iam trying to (selected check list lead ids ,text field  have  ( i
        written something  the text field)     message will be sent  the
        particular lead emails) how to solve plz tell me……… but the error
        occured

        public class leadmails {

           
        public leadmails()
        {
        }

        private final List leadids;
          public List ld;
          public leadmails(ApexPages.StandardController controller)
          {
             ld = [select Id from lead limit 10 ];
             for(Integer i=0;i<10;i++)
             {
                 leadids.add(ld[i].Id);
              } 
          }

           
        public class leadwrap
        {

        public ID id;
        public string lname{get;set;}
        public string company{get;set;}
        public string email{get;set;}
        public boolean check{get;set;}
        public string emailtext{get;set;}
        }
         list lw = new list();
         public list getinfo()
         {
         list ls=[select id,name, Company,email,emailtext__c from lead];
         for(lead l:ls)
         {
         leadwrap w = new leadwrap();
         w.id=l.id;
         w.lname=l.name;
         w.company=l.company;
         w.email=l.email;
         w.emailtext=l.emailtext__c;
         lw.add(w);
         }
         return lw;
         }
         list dlist=new list();
         lead le;
         public pagereference send()
         {
         for(leadwrap lp:lw)
         {
         if(lp.check == true)
         {
         le=[select id from lead where id=:lp.id];
         dlist.add(le);
         }
         }
         update dlist;
         
         pagereference pr= page.leadmail;
         pr.setredirect(true);
         return pr;
         
         
          
         
         Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
               mail.setTargetObjectIds(leadids);
               mail.setTemplateId(”);
              Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
        return null;

               }

  2. iam trying to (selected check list lead ids ,text field  have  ( i written something  the text field)     message will be sent  the particular lead emails) how to solve plz tell me……… but the error occured

    public class leadmails {

       
    public leadmails()
    {
    }

    private final List leadids;
      public List ld;
      public leadmails(ApexPages.StandardController controller)
      {
         ld = [select Id from lead limit 10 ];
         for(Integer i=0;i<10;i++)
         {
             leadids.add(ld[i].Id);
          } 
      }

       
    public class leadwrap
    {

    public ID id;
    public string lname{get;set;}
    public string company{get;set;}
    public string email{get;set;}
    public boolean check{get;set;}
    public string emailtext{get;set;}
    }
     list lw = new list();
     public list getinfo()
     {
     list ls=[select id,name, Company,email,emailtext__c from lead];
     for(lead l:ls)
     {
     leadwrap w = new leadwrap();
     w.id=l.id;
     w.lname=l.name;
     w.company=l.company;
     w.email=l.email;
     w.emailtext=l.emailtext__c;
     lw.add(w);
     }
     return lw;
     }
     list dlist=new list();
     lead le;
     public pagereference send()
     {
     for(leadwrap lp:lw)
     {
     if(lp.check == true)
     {
     le=[select id from lead where id=:lp.id];
     dlist.add(le);
     }
     }
     update dlist;
     
     pagereference pr= page.leadmail;
     pr.setredirect(true);
     return pr;
     
     
      
     
     Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
           mail.setTargetObjectIds(leadids);
           mail.setTemplateId(”);
          Messaging.SendEmailResult [] r =  Messaging.sendEmail(new Messaging.massEmailMessage[] {mail});
    return null;

           }
           }

      1.  hi
        error is     Illegal assignment from LIST to LIST
        Error occurred
        loading controller ‘leadmails’ for page leadmail

        and my requirment is like  selected check list lead ids ,text field  have  ( i written something 
        the text field)     message will be sent  the particular lead emails)
        how to solve plz tell me……… but the error occured

  3. Hi.. This is wonderful and very helpful post. I have tried this and it works like a charm. Thanks a bunch for this post… I have one question here, Can we use this rest api to send attachments from one SF org to other same like what have you done with Accounts?

    1. Hello @disqus_YusS9Xpwpw:disqus ,

      Can you please guide if it is possible to move few content files from one SF org to other?

  4. Hi , Above code not working for me…
    I am getting error…”Some error occurred, please try again”

    Regrads-
    Kapil

      1. How we will get more than one organization data lets say…
        We have 3 different sales force account (Org1, Org2, Org3)…
        Want to acccess all three data at a time…?

      2. Dynamic dependent pick list using apex : i created one Location__c object in that i Created two Pick Lists Country__c and State__c in Country__c pick list i added India,pakistan valus and in state__c pick list i added Andrapradesh,Madhyapradesh,lohore,Quetta if i select a value as India from Country__c pick list in State__c only able to see Andrapradesh,Madhyapradesh if i select a value as pakistan from country_c picklist in state__c only able to see lohore,Quetta by using apex

  5. How we will get more than organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

    Thanks in advance…. Kapil

  6. How we will get more than one organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

    Thanks in advance…. Kapil

  7. How we will get more than one organization data lets say…
    We have 3 different sales force account (Org1, Org2, Org3)…
    Want to acccess all three data at a time…?

  8. Hey first of all, congrats for putting up an excellent tutorial.

    Two questions:
    1) Are the remote site settings going to be same once we set it?
    2) How can be insert multiple records to other org via just one http callout since there is restriction on number of callouts?

    Appreciate your response.

    – Vishal

  9. I’m getting an error because of the SFDC instance.

    On one of my orgs , I have na11 so I added an endpoint to it. But I have another on na17 and it doesn’t works when try to do the httprequest to na17.

    Is there a way to fix this without creating an endpoint for each possible instances?

    Thanks in advance

      1. Thanks for your quick response! I’ve added it and it’s working now.

        But I think it will fail again if the instance change to another one (suppose na16).

        I was wondering if there is a way to prevent that, without adding one site setting for each of the possible instances (na1 to na21 & cs1 to cs32)

        1. It’s actually security in salesforce that you cannot connect to external websites if its not added in remote settings. So no way to bypass .

  10. I am getting below problem
    System.HttpRequest[Endpoint=https://www.salesforce.com/services/Soap/u/22.0, Method=POST]
    15:01:47.804 (804200848)|CALLOUT_RESPONSE|[33]|System.HttpResponse[Status=Server Error, StatusCode=500]

      1. it simply doesnot fetch account details…even after proving the correct username and password 🙁
        it says – Some error occurred, please try again. Please help.

  11. It’s working without any issues…and fetching Account records too, but while I am trying to fetch other object records like contact am not able to get, please help, and one more request can you please show how can we fetch multiple object records at a time..

    Thank you
    Kruti

      1. Hello @JitendraZaa:disqus

        I am getting the same error.
        Getting error at 67-Attempt to dereference a null object
        System.HttpResponse[Status = server error,Status code=500]
        Please help

  12. I am getting below error message..please help
    (17114034)|CALLOUT_REQUEST|[76]|System.HttpRequest[Endpoint=https://www.salesforce.com/services/Soap/u/22.0, Method=POST]
    10:32:57.0 (496655457)|CALLOUT_RESPONSE|[76]|System.HttpResponse[Status=Server Error, StatusCode=500]

  13. I tried to access the visual force page form one dev org to other org. I have downloaded the prtner wsdl for org1 and generated the apex class from wsdl file in org2. So I can able to login using login call in the apex class. I got he session URL and sessionID. Now i need to access the vf page in org1 to org2. May i know how i can use the sessionid generated while making login call. I was added the org1 vf page in the iframe which is org2. Please help me on the approach.

  14. Hi..Is it possible to perform update on the fetched data from external system without SAVING the same in salesforce and sending the updates back to the external system by using web service callout?

  15. Hi @JitendraZaa:disqus

    Thanks again for the wonderful post. Your posts are really very knowledgable and very helpful in polishing the technical skills.

    I was playing around with some deep concepts of REST web services. I found that we can’t fetch more then 2000 records. To overcome this I tried using “NextRecordsUrl” to fetch all records greater than 2000 and I am facing some challenges in that.

    Just wanted to know if you have some sample snippet to share with which we can fetch more than 2000 records using REST API.

    Regards

  16. Hi @JitendraZaa:disqus ,
    I want to login into another org using REST API without creating connected Apps.
    Is there any possible way to achieve this?

  17. Hi Jitendra Zaa,

    I have tried to connect org using above snippet
    getting error that : Some error occurred, please try again
    Tried using couple of orgs facing same issue for every org.

Leave a Reply