Salesforce: Consuming REST Web Service
Overview
Salesforce can act as a client calling an external REST API by utilizing Apex callouts. This article provides a step-by-step guide on how to consume a REST service in Salesforce.
Step 1: Enable Callouts
To enable callouts in Salesforce, follow these steps:
- Add the external endpoint to Remote Site Settings by navigating to Setup → Security → Remote Site Settings. This step is crucial as Salesforce blocks callouts by default.
Step 2: Apex Code to Consume REST Service
Below is a simple example of Salesforce consuming a REST API through Apex:
public class RestConsumerExample {
public static void getWeatherData(String city) {
// Prepare the HTTP request
Http http = new Http();
HttpRequest req = new HttpRequest();
// Example external REST API endpoint
String endpoint = 'https://api.example.com/weather/' + city;
req.setEndpoint(endpoint);
req.setMethod('GET');
// Add headers if needed (e.g., authentication)
req.setHeader('Authorization', 'Bearer YOUR_ACCESS_TOKEN');
req.setHeader('Content-Type', 'application/json');
// Send the request
HttpResponse res = http.send(req);
// Handle the response
if (res.getStatusCode() == 200) {
System.debug('Response Body: ' + res.getBody());
} else {
System.debug('Error: ' + res.getStatusCode() + ' ' + res.getStatus());
}
}
}
Step 3: Parsing JSON Response
To parse JSON responses in Salesforce, you can use JSON.deserialize to convert JSON into Apex objects. Here’s an example:
public class WeatherResponse {
public String city;
public String temperature;
public String condition;
}
public class RestConsumerExample {
public static WeatherResponse getWeatherData(String city) {
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather/' + city);
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer YOUR_ACCESS_TOKEN');
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
WeatherResponse wr = (WeatherResponse) JSON.deserialize(res.getBody(), WeatherResponse.class);
return wr;
} else {
throw new CalloutException('Failed with status: ' + res.getStatusCode());
}
}
}
Step 4: Test Class Example
It is essential to write test classes to validate the callout logic. Here’s a test class example:
@isTest
private class RestConsumerExampleTest {
@isTest static void testGetWeatherData() {
// Mock the HTTP response
Test.startTest();
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"city":"Cochin","temperature":"30C","condition":"Sunny"}');
// Use HttpCalloutMock to simulate the external service
Test.setMock(HttpCalloutMock.class, new WeatherMock());
WeatherResponse wr = RestConsumerExample.getWeatherData('Cochin');
Test.stopTest();
System.assertEquals('Cochin', wr.city);
System.assertEquals('30C', wr.temperature);
System.assertEquals('Sunny', wr.condition);
}
}
// Mock class
global class WeatherMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"city":"Cochin","temperature":"30C","condition":"Sunny"}');
return res;
}
}
Explanation
Here are some key points to remember while consuming REST services in Salesforce:
- Http & HttpRequest: Apex classes used for making REST callouts.
- Remote Site Settings: Required to whitelist external endpoints.
- Headers: Used for authentication such as Bearer tokens and API keys.
- JSON.deserialize: Converts JSON responses into Apex objects.
- Test.setMock: Necessary for unit testing callouts as Salesforce prohibits real HTTP calls in tests.
Key Takeaways
- Salesforce can function as a REST client using Apex callouts.
- Always configure Remote Site Settings for external endpoints to ensure smooth callouts.
- Utilize JSON.deserialize to effectively parse responses into Apex objects.
- Write mock-based test classes to validate the functionality of callouts.
