You will be charged % cancellation fee
|
Please Choose |
Full Order Select Items |
Learn how to easily interface with external services from Salesforce and access their data and functionality within the platform. This post covers how to set up an external service connection from an Open API specification, securely store API keys using named credentials, and add API endpoint URLs to Remote Site Settings.
Salesforce provides organizations of all sizes with a comprehensive suite of tools to manage their sales, marketing, and customer service operations right out of the box. However, there are often situations where Salesforce users need to access data or functionality that is not available within the platform. In such cases, connecting to an external API can be a powerful solution. By interfacing with an external API, Salesforce users can integrate data and functionality from other systems, enabling them to streamline their workflows, enhance their data analytics capabilities, and gain deeper insights into their customers. In this blog post, we will explore how Salesforce users can easily connect to external APIs and leverage their data and functionality within the Salesforce platform.
When connecting to an external API from Salesforce, it is necessary to first add the API endpoint URL to Remote Site Settings to ensure that Salesforce can communicate with the external API without encountering security errors. Perform the following steps as a user with sufficient permissions to access org-wide administrative settings:
Once you have added the API endpoint URL to Remote Site Settings, Salesforce will allow outbound connections to the external service from your Salesforce org. This helps to ensure that your integration with the remote API is secure and reliable.
It is important to note that adding a remote site to Remote Site Settings does not automatically authenticate with the external service. You will still need to provide authentication details, such as an API key or OAuth token, to authenticate with the API (detailed below). However, adding the remote site to Remote Site Settings is a crucial step in enabling communication between Salesforce and the external service.
Setting up an external service connection in Salesforce from an Open API specification is a straightforward process that can be completed in just a few steps. The first step is to create an External Service in Salesforce that represents the external API. To do this, navigate to Setup > External Services, click the “New External Service” button, then select the “From API Specification” option. You will be prompted to enter the details of the external service, including the endpoint URL, authentication settings, and any custom headers or parameters that are required (for demonstration purposes, we will use the PowerTools Community Edition API, which you can access for free by signing up for an account at https://www.apptigent.com/product/powertools-community-edition/).
NOTE: If you have not already setup a remote site URL as detailed above and provide a specification URL as opposed to a local file, you will receive an error similar to the following:
Assuming the API specification is valid, you will receive a confirmation screen with the raw JSON from the specification. Note that there is a fixed limitation of 100,000 characters for an input file. Larger specifications should be broken up into individual services, each with an input file less than 100,000 characters in length. There are also differences in how Open API 2.0 and 3.0 specifications are treated and the data types defined in the specification may not be fully supported by Salesforce (for more information on limitations, schema differences, data type support, and other limitations, refer to the following documentation: https://help.salesforce.com/s/articleView?id=sf.external_services_intro_schema_definitions.htm&type=5). Click ‘Next’ to continue once you have corrected any deficiencies in the specification definition that may cause it to fail validation:
Once you have created the External Service, the next step is to generate an Apex class that represents the external API’s methods and data structures. Select the API methods that you want to generate code for, and the wizard will generate the corresponding Apex classes.
With the Apex classes generated, you can now start calling the external service methods from within Salesforce. To do this from code, simply create an instance of the generated Apex class and call its methods. The Apex class will handle all of the communication with the external API, including authentication, serialization, and deserialization of data. To invoke the external service endpoints from Visual Flow or Process Builder, first add an Action to a flow, then select External Service and browse or search for the list of available endpoints:
When connecting to an external service that is secured with an API key, it is best practice to use a named credential in Salesforce to store the API key securely. This allows you to separate the authentication details from the rest of your code, making it easier to manage and update the credentials if necessary. Here are the steps to set up a named credential in Salesforce for access to an external connection secured with an API key:
Once you have created the named credential, you can use it in your Apex code to authenticate with the external API. To do this, simply reference the named credential in your Apex code using the syntax “{!$Credential.Name}”, where “Name” is the name of your named credential.
For example, if your named credential is called “MyExternalAPI”, you could use the following code to authenticate with the external API:
// Create an HTTP request object
HttpRequest req = new HttpRequest();
req.setEndpoint(‘{!$Credential.MyExternalAPI}/endpoint’); // replace ‘MyExternalAPI’ with the name of your named credential
req.setMethod(‘GET’);
// Add any necessary request headers
req.setHeader(‘Content-Type’, ‘application/json’);
// Send the HTTP request using the built-in HTTP class in Apex
Http http = new Http();
HTTPResponse res = http.send(req);
// Process the HTTP response
if (res.getStatusCode() == 200) {
// Parse the JSON response data
Map<String, Object> responseData = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
// Extract any relevant data from the response
String data = (String) responseData.get(‘data’);
// Do something with the data…
} else {
// Handle any errors or exceptions that may occur
System.debug(‘Error: ‘ + res.getStatusCode() + ‘ ‘ + res.getStatus());
}
In this example, we first create an HTTP request object and set the endpoint to the URL of the external API we want to connect to, using the named credential we created earlier. We then add any necessary request headers, such as the content type, and send the HTTP request using the built-in HTTP class in Apex.
Once we have received the HTTP response, we can process it using standard Apex code. In this example, we deserialize the JSON response data into a Map object, extract any relevant data, and then do something with it. If the HTTP response is not successful, we handle any errors or exceptions that may occur.
One important thing to keep in mind when working with external APIs is that they may change over time. If the external API’s Open API specification changes, you will need to regenerate the Apex classes in Salesforce to reflect those changes. Fortunately, Salesforce makes it easy to regenerate the Apex classes using the External Service Wizard, so you can keep your integration up to date with minimal effort.
In summary, setting up an external service connection in Salesforce from an Open API specification involves creating an External Service, generating Apex classes using the External Service Wizard, and then calling the external API’s methods from within Salesforce using the generated Apex classes. With this approach, Salesforce users can easily integrate with external APIs and take advantage of their data and functionality within the Salesforce platform.