Wednesday, 26 July 2023

Salesforce REST API | HTTP and Callout Basics | All You Need to Know

 

HTTP and Callout Basics

REST callouts depend on HTTP. To see how callouts work, it's useful to comprehend a couple of things about HTTP. Each callout demand is related to an HTTP technique and an endpoint. The HTTP technique shows what sort of activity is wanted. 

Zenith callouts to an outer help.

The least difficult solicitation is a GET demand (GET is an HTTP technique). A GET demand implies that the sender needs to get data about an asset from the worker. At the point when the worker gets and measures this solicitation, it restores the solicitation data to the beneficiary. A GET demand is like exploring a location in the program. At the point when you visit a site page, the program plays out a GET demand in the background. In the program, the consequence of the route is another HTML page that is shown. With a callout, the outcome is the reaction object. 

To outline how a GET demand functions, open your program and explore the accompanying URI: https://th-summit http-callout.herokuapp.com/creatures. Your program shows a rundown of creatures in an unusual organization in light of the fact that the assistance restores the reaction in a configuration called JSON. Once in a while, a GET reaction is likewise designed in XML

Coming up next are portrayals of regular HTTP techniques.

On the off chance that you have some spare time, peruse the thorough rundown of all HTTP techniques in the Resources segment

Notwithstanding the HTTP technique, each solicitation sets a URI, which is the endpoint address at which the assistance is found. For instance, an endpoint can be an interface/asset. In the model in the "HTTP and Callout Basics" unit, the endpoint is https://th-summit http-callout.herokuapp.com/creatures. 

At the point when the worker measures the solicitation, it sends a status code in the reaction. The status code demonstrates whether the solicitation was handled effectively or whether mistakes were experienced. On the off chance that the solicitation is effective, the worker sends a status code of 200. You've likely seen some other status codes, like 404 for a document not found or 500 for an inside worker mistake. 

On the off chance that you actually have leisure time subsequent to perusing the rundown of HTTP strategies, look at the rundown of all reaction status codes in the Resources area. In case you're struggling dozing around evening time, these two assets can help.

Get Data from a Service

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.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);
}
}

Send Data to a Service

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}

Test Callouts

public class AnimalsCallouts {
public static HttpResponse makeGetCallout() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserializes the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.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);
}
}
return response;
}
public static HttpResponse makePostCallout() {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody('{"name":"mighty moose"}');
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
return response;
}
}

Test a Callout with StaticResourceCalloutMock

To test your callouts, utilize mock callouts by either executing an interface or utilizing static assets. In this model, we utilize static assets and a false interface later on. The static asset contains the reaction body to return. Once more, when utilizing a counterfeit callout, the solicitation isn't shipped off the endpoint. All things being equal, the Apex runtime knows to look into the reaction indicated in the static asset and return it all things considered. The Test.setMock strategy educates the runtime that mock callouts are utilized in the test technique. How about we see mock callouts in real life. In the first place, we make a static asset containing a JSON-designed string to use for the GET demand.

In the Developer Console, select File | New | Static Resource. For the name, enter GetAnimalResource. For the MIME type, select text/plain, even though we are using JSON. Click Submit. In the tab that opens for the resource, insert the following content. Make sure that it is all on one line and doesn’t break to the next line. This content is what the mock callout returns. It’s an array of three woodland creatures.

{"animals": ["pesky porcupine", "hungry hippo", "squeaky squirrel"]}

You’ve successfully created your static resource! Now, let’s add a test for our callout that uses this resource. In the Developer Console, select File | New | Apex Class. For the class name, enter AnimalsCalloutsTest and then click OK. Replace the autogenerated code with the following test class definition.

@isTest
private class AnimalsCalloutsTest {
@isTest static void testGetCallout() {
// Create the mock response based on a static resource
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GetAnimalResource');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Associate the callout with a mock response
Test.setMock(HttpCalloutMock.class, mock);
// Call method to test
HttpResponse result = AnimalsCallouts.makeGetCallout();
// Verify mock response is not null
System.assertNotEquals(null,result,
'The callout returned a null response.');
// Verify status code
System.assertEquals(200,result.getStatusCode(),
'The status code is not 200.');
// Verify content type
System.assertEquals('application/json;charset=UTF-8',
result.getHeader('Content-Type'),
'The content type value is not expected.');
// Verify the array contains 3 items
Map<String, Object> results = (Map<String, Object>)
JSON.deserializeUntyped(result.getBody());
List<Object> animals = (List<Object>) results.get('animals');
System.assertEquals(3, animals.size(),
'The array should only contain 3 items.'
);
}
}

Press CTRL+S to save.

Select Test | Always Run Asynchronously. If you don’t select Always Run Asynchronously, test runs that include only one class run synchronously. You can open logs from the Tests tab only for synchronous test runs.

To run the test, select Test | New Run.

From the Test Classes list, select AnimalsCalloutsTest.

Click Add Selected | Run.


The test result is displayed in the Tests tab under a test run ID. When the test execution finishes, expand the test run to view details. Now double-click AnimalCallouts in the Overall Code Coverage pane to see which lines are covered by your tests.

Find out about utilizing callouts in triggers and in nonconcurrent Apex, and about making offbeat callouts. 

When making a callout from a strategy, the technique trusts that the outside assistance will send back the callout reaction prior to executing ensuing lines of code. Then again, you can put the callout code in a nonconcurrent strategy that is clarified with @future(callout=true) or utilize Queueable Apex. Thusly, the callout runs on a different string, and the execution of the calling strategy isn't hindered. 

When making a callout from a trigger, the callout should not obstruct the trigger interaction while hanging tight for the reaction. For the trigger to have the option to make a callout, the strategy containing the callout code should be explained with @future(callout=true) to run in a different string.