API Integration in Apex (Salesforce)

|
| By Charu Garg

Apex, the programming language used in Salesforce, provides robust features for integrating external APIs. By making HTTP requests to external web services, you can retrieve or send data between Salesforce and other systems.

Steps for API Integration in Apex

1. Define Remote Site Settings
Before making an external HTTP callout, Salesforce requires you to whitelist the target URL by adding it to Remote Site Settings.

Steps:

  • Go to Setup and then Remote Site Settings.
  • Click New Remote Site.
  • Enter the Site Name and the Remote Site URL.
  • Save the changes.

2. Make an HTTP Callout You can use the Http, HttpRequest, and HttpResponse classes to make API requests in Apex.

Example: GET Request

This example retrieves data from a public API.

public class ApiIntegrationExample {
public void makeGetRequest() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setMethod('GET');
try {
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
String responseBody = response.getBody();
System.debug('Response: ' + responseBody);
} else {
System.debug('Error: ' + response.getStatus());
}
} catch (Exception e) {
System.debug('Exception: ' + e.getMessage());
}
}
}

Example: POST Request

In this example, a POST request is used to submit data to an API.

public class ApiIntegrationExample {
public void makePostRequest() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
String requestBody = '{"name": "Abc", "email": "abc@example.com"}';
request.setBody(requestBody);
try {
HttpResponse response = http.send(request);
if (response.getStatusCode() == 201) {
System.debug('Data created successfully: ' + response.getBody());
} else {
System.debug('Error: ' + response.getStatus());
}
} catch (Exception e) {
System.debug('Exception: ' + e.getMessage());
}
}
}

Parsing JSON Response

Apex provides JSON class methods to parse JSON data from API responses.

Parsing a JSON response from a GET request.

Example: {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}

Apex code to parse the response:

public class ApiIntegrationExample {
public void parseJsonResponse() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/data');
request.setMethod('GET');
try {
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
String responseBody = response.getBody();
Map jsonData = (Map) JSON.deserializeUntyped(responseBody);
String name = (String) jsonData.get('name');
String email = (String) jsonData.get('email');
Integer age = (Integer) jsonData.get('age');
System.debug('Name: ' + name);
System.debug('Email: ' + email);
System.debug('Age: ' + age);
}
} catch (Exception e) {
System.debug('Exception: ' + e.getMessage());
}
}
}

Best Practices for API Integration in Apex

1. Use Named Credentials:
Simplifies authentication and endpoint management by storing credentials in Salesforce.
2. Error Handling:
Always implement robust error handling for network issues, API errors, or timeouts.
3. Governor Limits:
Be aware of Salesforce governor limits for callouts and ensure your code handles retries or bulk data processing efficiently.
4. Test API Callouts:
Use the HttpCalloutMock interface to test callouts in unit tests.

Leave a Reply

Your email address will not be published. Required fields are marked *