I need to call an external service FROM salesforce Authenticating against the External application is done via OAUTH so basically I need to write APEX code that uses HttpRequest and passes in the header OAUTH information like consumer key, secret etc.

Is there any code sample or documentation on this issue?


There are a couple ways that this can be accomplished.

1. Use a named credential You can set up a named credential that holds your connection information for your endpoint for your remote service. I prefer this route when possible as it does make it easier and less code to make your callouts to your services. The only disadvantage to this would be in cases where you have users that need to log in through individual accounts to the end point, and not a universal account for say - using an api for email sending like SendGrid. Making callouts using a named credential is much easier as you can use the below syntax ( per the documentation) to not have to gather and encode all of the information needed.

'callout: <namedcredential>/<path>'

2. Setup your own OAuth connection process This part will vary depending on how you will need to connect to your endpoint. If the External Application is hosted on Salesforce and you are able to connect via connected app, you can easier use Auth. Providers and Named Credentials that can be found in your Setup items. I use this often when connecting from one Salesforce org to another for some common integrations. Consumer Key and Secret are commonly stored here on the Auth. Provider.

I provided some links to the documentation that will outline how to use these processes, also some very basic code examples are there in the docs to help you build your connection. Give it a go and if after you have tried you find some issues, we will be happy to help you resolve your troubles.

Auth. Provider: https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_authproviders.htm

Named Credentials: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

HttpRequest Class: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httprequest.htm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.