Merge Fields for Apex Callouts That Use Named Credentials
To construct the HTTP headers and request bodies of callouts to endpoints that are
specified as named credentials, use these merge fields in your Apex code.
| Merge Field | Description |
|---|---|
|
{!$Credential.Username} {!$Credential.Password} |
Username and password of the running user. Available only if the named credential uses password authentication. For an example, see Non-standard authentication with username and password. |
| {!$Credential.OAuthToken} | OAuth token of the running user. Available only if the named credential uses OAuth authentication. For an example, see OAuth authentication. |
| {!$Credential.AuthorizationMethod} |
Valid values depend on the
authentication protocol of the named credential.
|
| {!$Credential.AuthorizationHeaderValue} | Valid values depend on the authentication protocol of the named credential.
|
| {!$Credential.OAuthConsumerKey} | Consumer key. Available only if the named credential uses OAuth authentication. |
Using {!$Credential.Username} and {!$Credential.Password} for non-standard authentication
1// non-standard authentication
2req.setHeader('X-Username', '{!$Credential.Username}');
3req.setHeader('X-Password', '{!$Credential.Password}');Using {!$Credential.OAuthToken} for OAuth authentication
1req.setHeader('Authorization', '{!$Credential.OAuthToken}');When you use merge fields to construct HTTP headers and request bodies, keep these considerations in mind.
- To allow Apex code to use merge fields to populate the HTTP header and request body with org data when the callout is made, a Salesforce admin must enable Allow Merge Fields in HTTP Header and Allow Merge Fields in HTTP Body on the named credential. See Create or Edit a Named Credential in Salesforce Help.
- To access or input custom headers, use Connect REST API. See Named Credentials Resources in the Connect REST API Developer Guide.
- When you use these merge fields in HTTP request bodies of callouts, you can apply the HTMLENCODE formula function to escape special characters. The
formula must start with HTMLENCODE, and other formula functions aren't supported. HTMLENCODE can’t be used on merge fields in HTTP headers. This
example escapes special characters that are in the
credentials.
1req.setBody('Username:{!HTMLENCODE($Credential.Username)}') 2req.setBody('Password:{!HTMLENCODE($Credential.Password)}') - When you use these merge fields in SOAP API calls, OAuth access tokens aren’t refreshed.