Integration Consuming API in Salesforce - 2

By in
302
Integration Consuming API in Salesforce - 2

In a previous post, we started discussing integrations and consuming Salesforce data. Today, we will continue that discussion with consuming API in Salesforce integrations and using JSON and Apex callouts.

It’s time to employ some Apex callouts to put our newfound HTTP understanding from part 1 to use. To obtain a list of forest creatures, this example performs a GET request to a web server. The response is delivered by the service in JSON format. The built-in JSONParser class transforms JSON, which is just a string, into an object. Then, the names of all the animals can be written to the debug log using that object.

JSON Apex callout Integration

You must authorize the callout’s endpoint URL, https://someurl.herokuapp.com, before you can run the examples in this unit.

 

  1. From the setup tools, launch the Developer Console (Setup gear icon).
  2. Select Debug | Open Execute Anonymous Window from the Developer Console.
  3. Remove the current code and add the next section.

 

Http http = new Http();

HttpRequest req = new HttpRequest();

req.setEndpoint(‘https://someurl’);

req.setMethod(‘GET’);

 

HttpResponse res = http.send(req);

// If the req is successful, parse the JSON response.

if(res.getStatusCode() == 200) {

// Deserialize the JSON string into collections of primitive data types.

Map<String, Object> results = (Map<String, Object>)                   JSON.deserializeUntyped(res.getBody());

// Cast the values in the ‘animals’ key as a list

List<Object> animals = (List<Object>) results.get(‘animals’);

System.debug(‘Received the following animals:’);

for(Object animal: animals) {

System.debug(animal);

}

}

 

  1. After choosing Open Log, click Execute.
  2. Select Debug Only when the debug log has opened to see the results of the System.debug statements.

 

Our example’s JSON is comparatively straightforward and simple to parse. Use JSON2Apex for JSON structures that are more intricate. For the purpose of parsing a JSON structure, this programme generates tightly typed Apex code. The tool produces the necessary Apex code for you when you simply paste in the JSON. Brilliant!

 

Conclusion

In this way, you can test your first API callout using Execute Anonymous Window in the Developer console.

 

Additional Resources

Cover Photo by Hunter Harritt on Unsplash

Leave a reply

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