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

16 thoughts on “Salesforce to Salesforce integration using Named Credentials in 5 lines”

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

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

  3. 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?

  4. @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?

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


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

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

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

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

      1. Try something like this:

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

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

Leave a Reply

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