Salesforce provides multiple ways to make HTTP callouts to external services, both using Apex code and declarative tools like External Services and Named Credentials. This tutorial will cover both methods in detail, with examples to help you implement them.
1. Making Callouts Using Apex
Step 1: Create an Apex Class
To make an HTTP callout in Apex, you need to create an Apex class that performs the callout. Here’s a simple example of making a GET request to a public API that retrieves user data.
public class UserApiCallout { // Method to perform the callout @Future(callout=true) public static void getUserData() { try { // Create a new HTTP request HttpRequest req = new HttpRequest(); req.setEndpoint('https://jsonplaceholder.typicode.com/users/1'); req.setMethod('GET'); // Create an HTTP object to send the request Http http = new Http(); // Send the request and receive the response HttpResponse res = http.send(req); // Handle the response if (res.getStatusCode() == 200) { // Process the response, e.g., parse the JSON response String responseBody = res.getBody(); System.debug('Response: ' + responseBody); } else { System.debug('Error: ' + res.getStatus()); } } catch (Exception e) { System.debug('Exception: ' + e.getMessage()); } } }
Step 2: Call the Method
You can trigger the above method from a trigger, Visualforce page, or Lightning Component. For example, you could call it from an anonymous block of Apex code:
UserApiCallout.getUserData();
Step 3: Handle Authentication
If the API requires authentication (e.g., OAuth), you need to include the necessary headers in your request. Here’s an example with a Bearer token:
req.setHeader('Authorization', 'Bearer ' + yourAccessToken);
Step 4: Handle JSON Response
You can parse JSON responses using the JSON
class in Apex. For example, to parse a JSON response into a custom Apex object:
public class User { public String name; public String email; } User user = (User)JSON.deserialize(res.getBody(), User.class); System.debug('User Name: ' + user.name); System.debug('User Email: ' + user.email);
2. Making Callouts Using Declarative Tools
Step 1: Using Named Credentials
Named Credentials simplify callouts by handling authentication and endpoint details declaratively.
- Create a Named Credential:
- Go to Setup > Named Credentials > New Named Credential.
- Enter the required information:
- Label:
My API Credential
- Name:
My_APICredential
- URL:
https://jsonplaceholder.typicode.com
- Authentication Protocol: Select the appropriate one (e.g., Password Authentication, OAuth 2.0).
- Label:
- Save the Named Credential.
- Modify the Apex Code to Use Named Credential:
public class UserApiCallout { @Future(callout=true) public static void getUserData() { try { HttpRequest req = new HttpRequest(); req.setEndpoint('callout:My_APICredential/users/1'); req.setMethod('GET'); Http http = new Http(); HttpResponse res = http.send(req); if (res.getStatusCode() == 200) { String responseBody = res.getBody(); System.debug('Response: ' + responseBody); } else { System.debug('Error: ' + res.getStatus()); } } catch (Exception e) { System.debug('Exception: ' + e.getMessage()); } } }
Step 2: Using External Services
External Services allow you to declaratively integrate with external APIs without writing Apex code.
- Define the API Schema:
- Obtain the API schema in OpenAPI format (JSON).
- Go to Setup > External Services > New External Service.
- Upload your API schema.
- Create an Integration Procedure:
- Use Flow Builder to create a new Flow.
- Add an External Service action to the Flow.
- Select the operation you want to perform (e.g., GET, POST).
- Deploy and Test:
- Use the Flow in a Lightning page, button, or process to trigger the callout.
Step 3: Using Flows with Named Credentials
You can also use Named Credentials within Flows by leveraging the HTTP Callout feature (in beta at the time of writing).
- Create the Flow:
- Go to Setup > Flow > New Flow.
- Choose Record-Triggered Flow or Screen Flow depending on your use case.
- Add an HTTP Callout element.
- Configure the HTTP Callout to use the Named Credential created earlier.
- Configure the HTTP Callout:
- Select the Named Credential.
- Define the HTTP Method (e.g., GET, POST).
- Set the Endpoint (relative path).
- Optionally, add headers or body data.
- Test the Flow:
- Run the Flow and check for the correct response.
3. Best Practices
- Governor Limits: Be aware of Salesforce’s governor limits, especially the limit on the number of callouts per transaction.
- Error Handling: Implement proper error handling in both Apex and Flows to manage API errors gracefully.
- Security: Always use Named Credentials or similar methods to handle authentication securely.
- Testing: Use
HttpCalloutMock
in Apex tests to simulate callout responses and achieve 100% code coverage.
By following this tutorial, you can make HTTP callouts from Salesforce using both Apex and declarative methods, depending on your requirements and the complexity of the integration. As always, happy coding.