Demystifying Salesforce REST API Part 1: Understanding HTTP Request & Response Objects

Connecting your Salesforce org to external data sources is key to building robust solutions. In this post, we'll dive into leveraging Salesforce's REST API capabilities to seamlessly parse JSON data from the Random User Generator API.

Prerequisites:

  • Basic understanding of Salesforce and Apex.
  • Familiarity with JSON data format.

Step 1: Set up the Connection (Remote Site Settings)

Before making any external calls, we need to register the API endpoint in Salesforce. Navigate to Security Controls > Remote Site Settings and add a new entry:

Step 2: Understanding Parameters (Optional)

Most REST APIs utilize parameters, but this specific endpoint doesn't require them. However, it's good practice to be familiar with their structure:

Step 3: Crafting the HTTP Request in Apex

Salesforce provides the Http and HttpRequest classes for building and sending requests:

1
2
3
4
5
6
7
Http httpProtocol = new Http();
HttpRequest request = new HttpRequest();

// Set endpoint as your REST service URL
String endpoint = 'https://randomuser.me/api/';
request.setEndPoint(endpoint);
request.setMethod('GET');

Step 4: Retrieving the Response

Salesforce offers the HttpResponse class to handle responses:

1
2
HttpResponse response = httpProtocol.send(request);
String JSONresponse = response.getBody();

The JSONresponse string now contains the JSON data received from the source system. Refer to "Salesforce Rest API Integration Part 2: Parsing JSON in Salesforce" for detailed parsing instructions.

No comments:

Post a Comment

Powered by Blogger.