Salesforce to Salesforce integration using Named Credentials in 5 lines

I have already written article to integrate Salesforce with other Salesforce instance around 3 years back. In last 3 years, Salesforce has changed a lot. This time I will integrate Salesforce with other Salesforce only only in 5 lines of code, can you believe it  🙂 ? Check my old article, and its around 50+ lines of code with security control.

What is Named Credential ?

A named credential specifies the URL of a callout endpoint and its required authentication parameters in one definition. You can simplify the setup of authenticated Apex callouts by specifying a named credential as the callout endpoint. You can instead specify a URL as the callout endpoint and register that URL in your organization’s remote site settings. In that case, however, you handle the authentication in your code. Doing so can be less secure and especially complicated for OAuth authentication.

Long description short , “using Named Credential, we can make call out to external system without supplying username or Password”.

To connect with external system using “Named Credential”, we need to follow below steps

  1. Create Connected App
  2. Create Authorization Provider
  3. Define Named Credential
  4. Use Apex to connect in 5 lines of code

For first 2 steps, you need to go through this article which explains in detail how to define Connected App and Authorization Provider.

Creating Named Credential

Now, directly start with step 3 to create Named credential by navigating to “Setup | Administer | Security Controls | Named Credentials | New Named Credential “.

Provide below information in settings :

Label and NameAny suitable value. We will need Name to refer in Apex code
URLURL of Salesforce instance where we want to Connect
Identity Type Named Principal
Authentication ProtocolOAuth 2.0
Authentication ProviderSelect Authentication Provider created in step 2
Scoperefresh_token full
Named Credential Salesforce
Named Credential Salesforce

Make sure to check “Start Authentication Flow on Save” and click on Save. After clicking on “Save” new page will open to authenticate Salesforce Org using OAuth2 connected App. If authentication is success, you can see message like “Authenticated as <Salesforce Username>” as shown in below image.

Authenticated Named Credential in Salesforce
Authenticated Named Credential in Salesforce

Now execute below code in anonymous Apex and you should be able to see list of all REST API available in Salesforce instance.

HttpRequest feedRequest = new HttpRequest();
Http http = new Http();
HTTPResponse feedResponse = http.send(feedRequest);
while (feedResponse.getStatusCode() == 302) {
                feedResponse = new Http().send(feedRequest);

As you can see in above code, we are not supplying any credentials. syntax to use Named Credential is like

callout:[Named Credential Name]/[Callout URL of other Salesforce Org]

You can consume standard as well custom web-service of other org using this approach.

Error : System.HttpResponse[Status=Moved Temporarily, StatusCode=302]

Sometime you may get above error in Named Credential and that’s why in above code I have added below extra block

while (feedResponse.getStatusCode() == 302) { feedRequest.setEndpoint(feedResponse.getHeader('Location')); feedResponse = new Http().send(feedRequest); }

Related Posts


23 responses to “Salesforce to Salesforce integration using Named Credentials in 5 lines”

  1. Badan Singh Pundeer Avatar
    Badan Singh Pundeer

    Thanks Jitendra, Its more than awesome!

  2. Brad Avatar

    Thank you!

  3. Faiza Naz Avatar
    Faiza Naz

    I am try to connect my one dev org with my another dev org but when i try to authenticate named credentials .It gave me below error.

    We can’t log you in because of the following error. For more information, contact your Salesforce administrator.

    SAME_ORG_SSO: Cannot sign on into same org.

    I am providing my second dev org domain URL in the named credentials URL.Please let me know if i am doing something wrong.

    1. Jitendra Zaa Avatar

      It seems you are trying to access same org using Named credential. We need to separate Salesforce org for this example to be working.

  4. Gurditta Garg Avatar
    Gurditta Garg

    Hi Jitendra,

    My destination org has SSO enabled, now if i try to save Named Credentials in my source org then it redirect to the SSO page and then it goes no where and the status remains pending,

    Any thoughts on this??

    1. Jitendra Zaa Avatar

      Hi Gurditta, If only SSO is enabled then this will not work. As Named credential is used with supported Authenticators , Salesforce is one of them. One way is to enable Salesforce Login from My domain. Setup connection. Make sure users Password does not expire using profile. And disable Salesforce Login again from My domain. Let me know if it works.

  5. James johnson Avatar
    James johnson

    Jitendra, I got a connect and I’m getting stuff back which is good however, and this is due to lack of knowledge, how would I send a request to get, for example, accounts based off of an ID?

  6. JP Avatar

    @JitendraZaa:disqus Thanks for this post. I am getting session timeout or invalid session error. My question is I have 2 orgs A (Client) and B (Resource). Where should I create these items:

    Create Connected App –> Org B
    Create Authorization Provider –> Org A , I used consumer key and secret from Org B’s connected app
    Define Named Credential –> Org A
    Use Apex to connect in 5 lines of code –> Org A

    What I am missing?

    1. Unknown Avatar

      Yes… Finally… I am able to get the response from other org…

      Make sure that while creating named credentials.. you should give URI as “”

      I gave “” >>> Throwed the error…

      so correct URI is “”.

  7. BK Avatar

    Hi Jitendra,

    Please help with the below points.

    1. I already have a connected app which the external system used to communicate to sales force. so when i use Named credentials i should create one more? cant we give any name to the connected app name, is the name having any significance?

    2. External system has provided certificates as well. How ill i upload that in certificates and key, as i dont see an option.


  8. […] Salesforce to Salesforce integration using Named Credentials in 5 lines […]

  9. Ashray Joshi Avatar
    Ashray Joshi

    Im getting HTTP Code : 302. How do you fix this?

  10. Hitendra Avatar

    Hi Jitendra,

    This blog is really very helpful for me and implementing the process as you have mentioned in the blog.
    I am getting the following error in callout.

    “[{“message”:”Session expired or invalid”,”errorCode”:”INVALID_SESSION_ID”}]”
    Any advice on this.

    1. Lahiru Udara Kodikara Avatar
      Lahiru Udara Kodikara

      Did you fix this ?

      1. Unknown Avatar

        Yes… Finally… I am able to get the response from other org…

        Make sure that while creating named credentials.. you should give URI as “”

        I gave “” >>> Throwed the error…

        so correct URI is “”.

  11. ashi Avatar

    Followed all the steps mentioned here, but getting below error. Any suggestions would be appreciated.

    System.HttpResponse[Status=Moved Temporarily, StatusCode=302]

    1. Sravani Avatar

      Hi Any resolution for the above error.Iam also facing the same issue ystem.HttpResponse[Status=Moved Temporarily, StatusCode=302]

      1. Nikolaj Avatar

        Try something like this:

        Http http = new Http();
        HttpResponse response = http.send(request);

        while(response.getStatusCode() == 302) {
        response = new Http().send(request);

  12. Sudarshan Vatturkar Avatar
    Sudarshan Vatturkar

    How can I trigger the Oauth authentication flow for my Named Credential using apex? In my case I am not getting refresh_token for OAuth as security reason hence user need to press edit/save named credential after access_token expires. OAuth setup as per user identity type. Any help will be appreciate.

  13. raagveGuru Avatar

    Hi Jitendra

    I have implemented Named Credential to integrate b/w Sales and Service orgs with the guidance from this website and able to successfully integrate the orgs. However after successful api call, i’m trying to redirect service org page to edit an account page but it redirects to login page.

    I wanted to open the account page in edit mode. Please share your thoughts and guidance.

    Thanks in advance

  14. Akshay Avatar

    Thank you, Jitendra
    Really helpful for beginners like me
    I really like the way you have described in very detail with screenshots
    Akshay (Salesforce developer from Pune)

  15. Steve Nahm Avatar
    Steve Nahm

    Very helpful in setting up a Salesforce to Salesforce connection. However I suggest that you emphasize in the section for setting up the Named Credential that the URL must be the “classic” URL ( and not a Lightning URL ( With the latter I kept getting: HttpResponse[Status=Unauthorized, StatusCode=401] and Response body: [{“message”:”Session expired or invalid”,”errorCode”:”INVALID_SESSION_ID”}]. Once I changed to using the classic URL it worked.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading