Integration with external system is very common requirement in Salesforce application. For this we can go for declarative external service or create apex class for each type of integration. Declarative External Service can only work when OpenAPI schema is available so for other cases we have to go for apex class. In this post we will create a generic apex class for calling external system which can used with named credential also.
For creating generic class we have to add feature to get different parameters like header parameter, request parameters, endpoint urls, named credential information etc.
We will also add overridden methods to give different ways (with different parameters) to call this generic class.
Here are some methods exposed by this generic class to call external api
//Call any api without any request parameter and header parameter public HttpResponse get(string url) //Call any api with request parameter and without any header parameter public HttpResponse get(string url, Map params); //Call any api with any request parameter and header parameter public HttpResponse get(string urlornc, Map params,Map headers); //Call any API to create and update request public HttpResponse post(string url,Map headers, Map params); //Call any delete api public HttpResponse del(string url,Map headers, Map params);
if you see above method definition, we are asking header and request parameter using Map. This map key/value pair are used to create request URL parameter or body parameter. This code will create API url parameters based on given parameters in request.
We have URL as first parameter. This parameter can be direct url or it can be named credential also. To identify first parameters is url of external system or it is named credential, we can use below code.
In many request we need to set request header also. We are taking headers parameter also. Using below code, we are setting request header parameters
Complete Code for generic class:
HandleException class code is available in our blog Exception Logging in Custom Object : Salesforce Apex
Test above generic class:
1. Call Shopify API using get method and named credential
2. Call WhatsApp API using post method and direct url. See blog – Integrate Salesforce with WhatsApp using Twilio API for this.
2 comments
[…] external callout to Smarty Street address API. External callout code is available in another blog Generic Apex class for Calling External System. To store API detail, I have used named credential SmartyStreet which will store API url […]
[…] We can also use a generic apex class to connect any Shopify system. You can refer generic code from the post Generic Apex class for Calling External System. […]