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
- Create Connected App
- Create Authorization Provider
- Define Named Credential
- 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 Name||Any suitable value. We will need Name to refer in Apex code|
|URL||URL of Salesforce instance where we want to Connect|
|Identity Type||Named Principal|
|Authentication Protocol||OAuth 2.0|
|Authentication Provider||Select Authentication Provider created in step 2|
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.
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(); feedRequest.setEndpoint('callout:Salesforce_Org/services/data/v32.0'); feedRequest.setMethod('GET'); Http http = new Http(); HTTPResponse feedResponse = http.send(feedRequest); System.debug(feedResponse.getBody());
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 webservice of other org using this approach.