Apex BaseHttpClient
A base class to make it quick and easy to implement a Http Client. Designed primarily with JSON rest API's in mind, but could be used for other requests.
Install
git clone
cd
into foldersfdx force:mdapi:deploy -d ./src -w 10000 -u [username]
Classes
BaseHttpClient
: base class to make any type of HttpRequest. Doesn't transform responsesBaseHttpJsonClient
: ExtendsBaseHttpClient
with automatic deserialization of JSONBaseHttpClientTest
: unit tests
will eventually implement an BaseHttpXMLClient
should I ever need one. (PR's welcome)
Usage
Extend one of the abstract classes
public class SuperDuperClient extends BaseHttpJsonClient {
public SuperDuperClient(){
super('callout:SuperDuper');
//optionally set this if you want sandbox request to go elsewhere
this.baseSandboxEndpoint = 'https://superduper-mock.api';
}
// implement public client methods
public SuperDuper getSuperDuper(String fooParam, String barBody){
return (SuperDuper) request(
'GET', //method
'foo', //url
new Map<String,String>{ //params
'foo' => fooParam
},
barBody, //body
SuperDuper.class //response type
);
}
}
Customize
If you need to change the way any of the default behavior works, you can easily do so by overriding any of the methods. A common use case would be to override the genRequest
method to add headers:
protected override HttpRequest genRequest(String method, String uri){
//call super method to init request
HttpRequest req = super.genRequest(method, uri);
// add some headers
req.setHeader('X-API-KEY', 'xyz');
req.setHeader('accept', 'application/json');
return req;
}
With the BaseHttpJsonClient
you can override the parseResponse
method if you needed to rename reserved keywords, etc. The following example shows how this might look if you were using the APEX-JSONReservedNameSerializer method.
protected override Object processResponse(HttpResponse resp, Type returnType){
String resBody = resp.getBody();
return SuperDuperJson.deserialize(resBody, returnType);
}
Call
SuperDuperClient spc = new SuperDuperClient();
SuperDuper sp = spc.getSuperDuper('fooooooo', 'bar!');