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

  • Arunarapolu

    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.

  • Anonymous

    Hi,
    Please add “https://www.salesforce.com” in remote site. Let me know if you face error.

    Regards,
    Jitendra Zaa

    • siva

      SAME ERROR IS FACING GIVING REMOTE SITE As you said

    • Ramadhar Mishra

      I’m also trying to run same example in my dev org. I’ve added following Remite site sessings urls.

      1) https://www.salesforce.com

      2)https://ap1-api.salesforce.com

      3)https://www.na5-api.salesforce.com

  • Anonymous

    sir i want to hello world program plz send mail

    • Anonymous

      Hello world program of what?
      if you are talking about the salesforce tutorial from starting then this article might be very useful to you.
      http://JitendraZaa.com/blog/salesforce/step-by-step-salesforce-tutorial-creating-custom-object-1-of-n/

      Regards,
      Jitendra Zaa

      • Sukumar

        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;

               }

  • Sukumar

    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;

           }
           }

    • JitendraZaa

      Hi,
      What actually you are trying to achieve and what error you are getting?

      • Sukumarmalladi22

         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

  • Milan Sanghani

    hi,
    Can we access junction object record from one org to another org using this Rest Api.

    • JitendraZaa

      Yeah.. With help of REST API.. you can do it

  • Vikram

    HI, how do I soap Login in customer portal….

    Its Urgent

  • saurabh

    How can I get access token for rest api using window phone .net4.5 vs2012

  • Amit

    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?

    • JitendraZaa

      Yes we can

      • Amit

        Could you please provide me the example of the same.

      • sudha

        hi i m getting error like

        Some error occurred, please try again

        pls help me out

  • Alex

    Do the remote site details need to be configured on in the Salesforce instance that is requesting or giving the records?

  • JitendraZaa

    Have you tried to adding Salesforce.com also in Remote Site Setting?

  • sunil

    Unknown property ‘account.name’ im getting this error

  • kapil p

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

    Regrads-
    Kapil

  • kapil p

    Hey As a password filed need type only password OR Password+Security Token.

  • hareesh

    thanks its working for me

  • aritra mukherjee

    excellent 😀 @JitendraZaa:disqus

    • JitendraZaa

      Thanks Bhai..

      • hareesh

        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…?

      • hareesh

        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

  • Guest

    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

  • kapil p

    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

  • hareesh

    how to geti multiple organizations data at a time

  • hareesh

    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…?

  • Vishal

    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

  • Ankush Somani

    can you tell me how to invoke apex class method of one org from another org. ?

  • oo

    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

    • JitendraZaa

      What error you are getting ? Have u added na17 in remote site setting ?

      • oo

        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)

        • JitendraZaa

          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 .

          • oo

            ok, thank you, and great post!

          • Muneendar

            can u please provide step by step document.Send the mail

            “muneendar.sforce@gmail.com”

  • Ravi

    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]

  • raju

    Hi,
    How to move one Data to another org using apex in salesforce?

    thanks,

  • raju

    Hi,
    How to move one Organization Data to another organization using apex in salesforce?
    Example:Account
    thanks,

  • Chethan Jagan

    This does not work dude 🙁

    • What error you are getting?

      • Chethan Jagan

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

        • Chethan Jagan

          Jitendra – You know why is it not fetching the records?

      • Chethan Jagan

        You know why is it not fetching the records?

  • Nilesh

    Is there any limitation for the number of times we can call? like normal API limit is 15000/day

  • Kruti

    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