Activity › Forums › Salesforce® Discussions › How to Perform a callout to send data to an external service in Salesforce ?
-
How to Perform a callout to send data to an external service in Salesforce ?
Posted by Kirandeep on February 24, 2020 at 4:50 PMHow to Perform a callout to send data to an external service in Salesforce ?
Deepak replied 6 years, 3 months ago 2 Members · 1 Reply -
1 Reply
-
Hi Kirandeep,
I’am going to perform a callout to send data to an external service in Salesforce by taking an example:
For instance, when you buy the latest Justin Bieber album or comment on your favorite “Cat in a Shark Costume Chases a Duck While Riding a Roomba” video, your browser is making a POST request to submit data.
Let’s see how we send data in Apex.
This example sends a POST request to the web service to add an animal name.The new name is added to the request body as a JSON string.
The request Content-Type header is set to let the service know that the sent data is in JSON format so that it can process the data appropriately.
The service responds by sending a status code and a list of all animals, including the one you added.
If the request was processed successfully, the status code returns 201, because a resource has been created.
The response is sent to the debug log when anything other than 201 is returned.
- Open the Developer Console from the Setup gear ( ).
- In the Developer Console, select Debug | Open Execute Anonymous Window.
- Delete any existing code and insert the following snippet.
- Select Open Log, and then click Execute.
- When the debug log opens, select Debug Only to view the output of the System.debug statement. The last item in the list of animals is “mighty moose”.
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()); }Hope it helps.
Log In to reply.