Salesforce Integration

Salesforce Apex Callouts using REST

Salesforce provides an easy way of making an external Web services call from your Apex and the mechanism is called Apex Callouts. Apex provides integration with Web services that either utilize SOAP and WSDL or HTTP (RESTful) services. In this article I will be using the REST option to invoke a web service. As a refresher, REST (Representational state transfer) is a way of invoking web services using a uniform and predefined set of stateless operations. In case, you want to know about the Apex Callouts using SOAP, you can read my other article – Salesforce Apex Callouts using SOAP.

There are many free REST web services provider available on the internet but the one I found most appropriate for this tutorial is from https://jsonplaceholder.typicode.com/ and will be using their ‘POSTS‘ web service. You can go to this link and look at their JSON response – Get All Posts. Now, let’s jump on to the required setup and Apex code below.

Remote Site Settings – Before we can make web service call, we need to setup the end point/URL in the Remote Site Settings for the particular destination otherwise Salesforce security will not let you make calls and you will receive errors. So before we proceed further with the code, go to ‘Administrative Setup | Security Controls | Remote Site Settings’, and click ‘New Remote Site’ and put the details as shown below.

Static Resource – Since Salesforce does not allows test methods to invoke the actual web service, we would be using the content of a static file as our fake response in our Apex test class for GET method only. For the POST method fake response, we will use a different approach using the code itself. So go to the developer console, create a new Static Resource as ‘File | New | Static Resource’ with mime type as ‘text\plain’. Name the file as – ‘GetAllPosts’, copy-paste the  below content and save it.

Apex Classes

Note – If you want to use the code below, make sure to remove the special characters which might appear after copying to your editor.

I have provided the Apex code only for the ‘GET’ & ‘POST’ Http methods call. You can follow and develop for other methods such as ‘PUT’, ‘PATCH’ and ‘DELETE’.

ApexRestCallout – This class contains 2 methods, each invoking the GET and POST methods of the REST web service. In the GET, we are getting the first 100 posts from them and in the POST method we are creating a new one.

ApexRestCalloutHttpMock – This class is used to generate a fake response for POST method.

ApexRestCalloutTest – This class contains the test method implementation which invokes and uses the fake response to test the coverage of the ApexRestCallout class and provides 100% coverage.

Feel Free to provide your valuable comments or point out any issues or scope of improvement in the above post.