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.
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”

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.

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>
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.
Hi,
Please add “https://www.salesforce.com” in remote site. Let me know if you face error.
Regards,
Jitendra Zaa
SAME ERROR IS FACING GIVING REMOTE SITE As you said
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
sir i want to hello world program plz send mail
Hello world program of what?
if you are talking about the salesforce tutorial from starting then this article might be very useful to you.
https://jitendrazaa.com/blog/salesforce/step-by-step-salesforce-tutorial-creating-custom-object-1-of-n/
Regards,
Jitendra Zaa
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;
      }
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;
      }
      }
Hi,
What actually you are trying to achieve and what error you are getting?
 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
hi,
Can we access junction object record from one org to another org using this Rest Api.
Yeah.. With help of REST API.. you can do it
HI, how do I soap Login in customer portal….
Its Urgent
How can I get access token for rest api using window phone .net4.5 vs2012
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?
Yes we can
Could you please provide me the example of the same.
hi i m getting error like
Some error occurred, please try again
pls help me out
Hello @disqus_YusS9Xpwpw:disqus ,
Can you please guide if it is possible to move few content files from one SF org to other?
Do the remote site details need to be configured on in the Salesforce instance that is requesting or giving the records?
Have you tried to adding Salesforce.com also in Remote Site Setting?
Unknown property ‘account.name’ im getting this error
Hi , Above code not working for me…
I am getting error…”Some error occurred, please try again”
Regrads-
Kapil
Hey As a password filed need type only password OR Password+Security Token.
thanks its working for me
excellent 😀 @JitendraZaa:disqus
Thanks Bhai..
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…?
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
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
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
how to geti multiple organizations data at a time
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…?
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
can you tell me how to invoke apex class method of one org from another org. ?
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
What error you are getting ? Have u added na17 in remote site setting ?
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)
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 .
ok, thank you, and great post!
can u please provide step by step document.Send the mail
“muneendar.sforce@gmail.com”
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]
Hi,
How to move one Data to another org using apex in salesforce?
thanks,
Hi,
How to move one Organization Data to another organization using apex in salesforce?
Example:Account
thanks,
Its very easy, check this – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/
This does not work dude 🙁
What error you are getting?
it simply doesnot fetch account details…even after proving the correct username and password 🙁
it says – Some error occurred, please try again. Please help.
Jitendra – You know why is it not fetching the records?
You know why is it not fetching the records?
Is there any limitation for the number of times we can call? like normal API limit is 15000/day
It uses API limit, check this documentation – https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_api.htm
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
Hi Kruti, are you able to fetch contact from normal SOQL query ? also, please check this new blog with less code – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/
Throwing this Error ,Find below Attached Please Help To me
Can you check developer console to get exact error detail or you can try this other approach – https://www.jitendrazaa.com/blog/salesforce/salesforce-to-salesforce-integration-using-named-credentials-in-just-5-lines-of-code/
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
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]
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.
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?
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
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?
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.
followed the same steps and all alternate options but Getting error – System.CalloutException: Unexpected end of file from server.
Please Guide..
I have TWO logins one for USA and one for CAN. A case gets created in CAN, somehow should be created/shared to USA instance. how is this possible using the above? please advice.
Hi, Thank you very much and it is working fine. I am getting the records from one to org to other org. Now I want to get these records to be inserted into the object. Please let me know how?
Hi ,
In the above code, we are able to get the records from account object and only for some fields.Could you please let me know on how to get all the fields of the account object with the above code.
Thank you.
Hi Jitendra,
I have implemented following process in my 2 orgs.
1. Service Provider Org – https://n26developerorg-dev-ed.my.salesforce.com
>> I have created Connected App in this org.
>> This contains my Accounts
2. IDP – https://pulkitsharma1313-dev-ed.my.salesforce.com
>> I have created Auth Provider & Named Credentials & Remote Site Settings here
>> I want to fetch accounts in this org.
3. I have implemented above code and getting following error:-
System.CalloutException: Unable to tunnel through proxy. Proxy returns “HTTP/1.1 503 Service Unavailable”
I have added IP Ranges as well and added Security Token in Password before submitting fetch button.
Please help!!
Hi Jitendra,
I tried above steps and did following in my 2 dev orgs
1. Service Provider – https://n26developerorg-dev-ed.my.salesforce.com
>> Created Connected App
>> Contains Account Data
2. IDP – https://pulkitsharma1313-dev-ed.my.salesforce.com
>> Created Auth Provider, Named Credentials & Remote Site Settings
>> In Remote Site Setting – Added above SPs URL
>> Want to Fetch Account Data from above SP org.
3. Used the same class and VF Page, but getting following error:-
>> NOTE:- Used Username & Password with Security Token
Error – System.CalloutException: Unable to tunnel through proxy. Proxy returns “HTTP/1.1 503 Service Unavailable”
Please help!!
Thanks,