There is a new open source framework for simplifying HTTP Callouts in apex. This framework can be deployed to any salesforce org by click of a button and has some great features like:-
- All the callout information is configurable using custom metadata.
- You don't have to define different mock classes for test coverage of each callout. There is a pre defined generalized mock class that you can use.
- Named credentials are supported.
- Asynchronous callouts are very easy to implement in VF Pages as well as in lightning components.
- Test coverage for request and responses are covered automatically.
For example, I have made a dry api at:- https://sfdcstop.herokuapp.com/blogs which gives us a simple JSON response similar to the one as shown below:-
"author": "Rahul Malhotra",
"title": "Salesforce Integration Tutorial Part 1 - Introduction and Setting up Workbench",
"title": "Salesforce Integration Tutorial Part 2 - Exploring GET Method",
So, once I have installed the framework in my org. To hit this API from Salesforce, I simply created a remote site setting record:-
And I created a record of my HTTPCalloutConfiguration metadata as shown below:-
You can see above that my metadata has a name SFDCStopBlogs and I have specified all the necessary information that I need for my callout in my metadata record like:- Request method, Endpoint URL, Header parameters, URL parameters, Request body, Timeout etc.
And that's it. In order to call my API, I can simply execute a single line of code in my developer console like:-
HttpCalloutService service = new HTTPCalloutService('SFDCStopBlogs');
So, I just created an instance of my HTTPCalloutService class, passed the metadata name in the constructor and added some debug statements in which the first debug is printing the request and inside the second debug, we're sending the request and returning the response body which is printed. Once, you'll execute this statement, salesforce will perform a callout using the framework and you'll get an output as shown below:-
As you can see above we're getting a successful response from the API. So, that's how you can very easily setup a callout from salesforce using HTTPCalloutFramework. To know more or install the framework you can checkout the github repository here:- https://github.com/rahulmalhotra/HTTPCalloutFramework
Hope It helps :-)