Retrieving callout URL for the new generation of Named Credentials

2 minutes de lecture
Named credentials

At the end of last year, Salesforce has announced the next generation of Named Credentials. This new generation, coupled with External Credentials, extends what was previously possible with the legacy ones. For instance, you can give fine-grained access to your credentials, with different Authentication Parameters assigned to separate Permission Sets, allowing you to authenticate with different access rights depending on the Permission Set assigned to your users.

All the new features have been described in a great blog post on Salesforce Developer Blog.

One of the question that I saw several times about this new generation is how to retrieve the associated URL. With the legacy version, it was as easy as an SOQL query:

SELECT Endpoint FROM NamedCredential WHERE DeveloperName = 'MyNamedCredential'

However, as stated in the documentation, this field is only valid for legacy Named Credentials.

Until now, there wasn’t an easy way to retrieve this URL for the new Named Credentials in Apex. You could still query the NamedCredentialParameters table (SELECT DeveloperName, (SELECT ParameterValue FROM NamedCredentialParameters WHERE ParameterType = 'Url') FROM NamedCredential WHERE DeveloperName = 'MyNamedCredential'), but this one was only available in the tooling API.

Starting the Winter ’24 release, you’ll be able to get it very easily in Apex via the new getNamedCredential() method:

ConnectApi.NamedCredential nc = ConnectApi.NamedCredentials.getNamedCredential('MyNamedCredential');
System.debug(nc.calloutUrl);

Using ConnectApi instead of an SOQL query also brings namespace protection to your credentials.

You can find the documentation of the new method here.

If you want to learn more, check out the article Apex Replay Debugger.

A lire également sur le blog