SFDC Stop - Always the latest about Salesforce


Full Tutorial Series with videos, free apps, live sessions, salesforce consulting and much more.

Saturday, 15 February 2020

Salesforce Integration Tutorial Part 13 - Creating a Test Class for a SOAP Web Service in Apex

Hello Trailblazers,

Welcome to the 13th tutorial of the Salesforce Integration Tutorial Series. In the previous tutorial, we created a SOAP web service in apex. You can have a look at that tutorial by clicking here. In this tutorial, we're going to create a test class for a SOAP web service.

Let's have a look at the below code:-

As  you can see above, we have a webservice method in our ContactResource class. This method takes an integer which is the limit of contacts. Then, we query some contacts from our org using that limit and return the list of contacts in the response.

Now it's time to create a test class for the same. The test class for this web service will be exactly the same as we make a test class for a normal apex class. We just have a method which is accepting an integer as a parameter and returning a list of contacts. I created a new test class for our ContactResource class named as ContactResourceTest. Let's have a look at the code below:-

As you can see above, we have a TestSetup method which is creating 5 contacts with name Rahul Malhotra. This is our test data. Then, we have a testGetContactIdAndNames method which is simply calling the getContactIdAndNames method of our ContactResource class by giving the integer 1 in the parameter. That method is returning a list of contacts which we have stored in returnedContacts variable. Finally, we're just checking that our returnedContacts list is not null, has a size of 1 and the contact inside that list has a name of Rahul Malhotra. So, we just checked that our method is working as expected and when you'll run this test class, you'll find that our ContactResource class is covered with 100% coverage as shown below:-


That's all for this tutorial. You have successfully created a test class for a SOAP Web Service class in apex. You can find the code for the web service and test class in the soapapi branch of my SFDC-Integration-Tutorial github repository by clicking here.

Do checkout the other tutorials in this whole integration tutorial series by clicking here. If you liked this tutorial, make sure to share it in your network and let me know your feedback in the comments section down below.

Happy Trailblazing..!!

Sunday, 9 February 2020

Salesforce Integration Tutorial Part 12 - Creating a SOAP Web Service in Apex

Hello Trailblazers,

Welcome to the 12th tutorial of the Salesforce Integration Tutorial series. In the previous tutorial, we created a mock class and a test class for our SOAP API callout. You can find that tutorial by clicking here. In this tutorial, we're mainly going to create a web service i.e. a custom SOAP API in Salesforce.

Remember the 2nd tutorial of Integration Tutorial Series in which we created a custom REST API and explored GET method in detail ? Let's recall that code by having a look below:-

As you can see above, we have a method named as:- getContactIdAndNames() which is called when we make a get request to this API. Inside this method, we're getting the contactLimit i.e. the number of contacts to be queried as a URL parameter and we're returning a list of contacts in the response.

Creating a custom SOAP API

Now, I am going to convert the same method into a webservice method so that it's converted into a SOAP API and then we'll generate a WSDL file for it and call it from SOAP UI client. If you're not aware of SOAP UI, please have a look at this tutorial first and then you can come back to the current tutorial as we're going to use SOAP UI client to hit our custom SOAP API and get the response.

Let's have a look at the updated code below:-

As you can see above, I removed all the annotations like:- @HTTPPost @RestResource etc. as we don't need them in case of defining a SOAP API. All we need is a global class with a static method defined with webservice keyword. The number of contacts to query that we were giving previously as a URL parameter are now given in the method parameter named as:- contactLimit. After that we're simply querying the contacts and returning the list of contacts in the response.

And that's all. You have successfully created a custom SOAP API in Salesforce. SOAP APIs basically support GET and POST HTTP Methods according to the w3 specifications defined here:- https://www.w3.org/TR/2007/REC-soap12-part0-20070427/#L26854 but we mostly use POST in case of SOAP requests as we have messages encoded in XML format. So, whenever you need to create a SOAP webservice in Salesforce, all you need to do is to define a static method in a global class with the keyword webservice. You can take the input as a parameter in method and the data returned by the method will be given in the response.

Generating a WSDL file

Now, it's time to test our custom SOAP API that will return the contact id and names of contacts present in salesforce and we can limit those contacts by giving the contactLimit in the input request XML. Remember, when we wanted to consume a SOAP API we used WSDL2Apex to generate an apex class from WSDL. In the same way you can generate a WSDL from your custom apex class. All you need to do is go to setup and search for apex classes. Click on Apex Classes under Develop and you'll see the below page:-


As you can see above in the ContactResource class I have an option of WSDL. Either you can click this or when you open the ContactResource class, you'll see a Generate WSDL button as shown below:-


On clicking this button you can see another xml which is the WSDL file for our custom SOAP API that we just created. It'll look similar as you can see below:-


You can provide this XML to the 3rd party who wants to consume your custom SOAP API and it'll be able to connect with Salesforce.

Testing our SOAP API using SOAP UI

Now we have the WSDL for our custom SOAP API. So, it's time to test our SOAP API. I have already imported the Enterprise WSDL into the SOAP UI and got the session id. If you want to learn that, you can have a look at another tutorial by clicking here. I am going to add our new WSDL to the existing project. To do that, just right click on the project and click on Add WSDL as shown below:-

You'll see a dialog as shown below:-


Choose your custom WSDL file and click on OK. When I tried to import the WSDL and clicked on OK button, I got some errors as shown below:-


These errors are coming because the WSDL file that we downloaded from Salesforce has some tags missing. For ex:- The first error is regarding the ChangeEventHeader which is not found in our WSDL file. However, I checked Enterprise WSDL and I was able to find the ChangeEventHeader as shown below:-


The other errors are related to some other type tags like:- json, stringList. You can find all the missing data in the enterprise wsdl and can copy from there to update your actual wsdl file.

I tried and added the ChangeEventHeader, json, and stringList xml types that were missing in my custom WSDL file below the schema tag as shown below:-


I tried to import my WSDL file in SOAP UI again and found that those 3 errors are resolved and I have some of the remaining errors that I need to resolve.


So, I updated the the custom API xml file again adding the missing contents and tried to import that file again. Finally, I got my XML imported into SOAP UI and our method getContactIdAndNames is available with the input XML request as shown below:-


I am also sharing the XML changes I did below, so that you can just add-on the same elements in your custom XML in case the error is exactly same. Otherwise you'll find all the missing elements in Enterprise XML from Salesforce.

Now, It's time to test our API. As you can see in the image below, I commented out the XML tags that I am not using, added the session id received from login request between the con:sessionId xml tag. Between the con:getContactIdAndNamesTag I have another tag named as con:contactLimit, which is nothing but the parameter of our apex method. I have specified the limit as 2 here as I just want to fetch 2 contacts from my org with Id and Name.


As you can see above, on the left hand side I have the request XML that I sent using the green play button above and on the right hand side, I have the response xml with 2 contacts queried from my Salesforce Org with Id and Name of each contact.

That's all for this tutorial. Today, you learned about creating a custom SOAP API in Salesforce and testing it using SOAP UI. You can find the code used in this tutorial in the soapapi branch of my SFDC-Integration-Tutorial github repository here. If you liked this tutorial, make sure to share it in your network and let me know your feedback in the comments down below.

Happy Trailblazing..!!

Saturday, 8 February 2020

How to connect to Salesforce using SOAP APIs ? SOAP UI Tutorial

Hello Trailblazers,

SOAP UI is a very popular API testing tool specially when we talk about SOAP APIs. So, in this tutorial, we're going to see how we can connect with Salesforce Org using SOAP UI and we will call a standard salesforce soap api and have a look at the response. If you want to learn about connecting with Salesforce using REST APIs you can have a look at this tutorial. So, let's begin:-

Download SOAP UI

You can download SOAP UI by going to https://www.soapui.org/downloads/soapui.html and you'll see the below screen:-


As you can see above, there are two options. For advanced testing, you can download SOAP UI Pro however, we're going to download SOAP UI Open Source for this tutorial. Just click on the green button and your download will start automatically. If not, you can also click on the click here link on the next page as shown below:-


Once you've downloaded SOAP UI, open the installer and follow simple steps to install SOAP UI. You can keep the settings as default as we don't need any specific configuration while installing SOAP UI. Once you've downloaded and installed SOAP UI, open that and you'll see a start page similar to as shown below:-


Salesforce Enterprise WSDL

So, you've downloaded and installed SOAP UI. The next step is to download enterprise wsdl file from your Salesforce Org. Go to setup and search for api and click on API under Integrations. You'll see the screen as shown below:-


Click on Generate Enterprise WSDL link and you'll see the below page:-


This page is showing the managed packages versions that are installed in your org that you want to use in SOAP API integration with Salesforce. As for this tutorial, we're not going to connect with any managed package so this doesn't matter to us. Click on the Generate button and you'll see an xml as shown below:-


Save this xml file in your system as you save any html page (Ctrl + S for windows) and that's all. Now it's time to create a new project in our SOAP UI and test a standard Salesforce SOAP API.

Connecting with Salesforce using SOAP UI

1. Open SOAP UI, go to the File menu and click on New SOAP Project.


2. You'll see a dialog as shown below:-


As you can see above, I have given the project name as:- SFDCStopOrg (you can give any name of your choice). In Initial WSDL field, I have selected the Enterprise WSDL file downloaded from my Salesforce Org. Click on OK button and a new project will be created and will be shown on the left hand side panel as shown below:-


As you can see above, there are a number of operations that we can perform in our Salesforce Org such as:- changing password, converting lead etc. using standard SOAP APIs that are available.

3. Login to Salesforce:- Before testing any operation, our first step as to login to salesforce as we did in case of REST APIs. Here also, we need to get a token to interact with our Salesforce Org. Out of the different operations that are available in the left panel, look out for login and click on the Request 1 available under that as shown below:-


You'll see an xml request shown on the right side with 4 fields that we can fill up namely:- organizationIdportalId in the header and usernamepassword in the body. We don't need to fill organization id and we don't have a customer portal too so you can simply remove the question marks (?) from these tags to make them empty and fill up the username between the urn:username tags and password appended with security token between the urn:password tags as shown below:-


If you don't know your security token you can simply go to user settings which you can find below your profile picture.


Click on settings and search for reset and you will find an option to reset your security token.


Click on Reset Security Token button and you'll receive a mail from Salesforce with a new security token that you can append with your password in the urn:password field. Once your login request is ready, click on the green play button to submit the request.


You can see the reponse of this request in the right panel as shown below:-


As you can see in the response above, there is a tag named sessionId that consist of the token which we need to use in all our API requests to Salesforce. Just above that there is another tag named serverUrl which is our server URL for making SOAP requests to Salesforce Org. Copy this session id and server url and let's open another request to fetch data from Salesforce. 

Executing a Query using SOAP UI

Let's have a look at the below request in which I am querying Accounts using SOAP UI. I selected the Request 1 under the query operation from the left hand sidebar. The server URL which we got from login request is set in the address bar and the session id is set between the request xml urn:sessionId tag. You can see that I have commented some of the tags as they were not required for our operation. I have specified the query as:- SELECT Id, Name FROM Account between the urn:queryString tag as shown in the below image.


Submit the request using the green play button and you'll get a response as shown on the right hand side in the image above. You can see that I am receiving the id and name of accounts in the response xml as queried from Salesforce.

Congratulations..!! You've successfully connected with Salesforce using SOAP UI and fetched a list of accounts using the standard SOAP API available for executing query. In the same way, we can add a wsdl to the same project for a custom SOAP API that we can create in Salesforce using apex and test the same. The server URL will be already present in that case when we import a custom API wsdl. That's all for this tutorial, if you liked it, make sure to share it among your network and let me know your feedback in the comments down below.

P.S.:- If you want to learn Salesforce Integration, check out:- Salesforce Integration Tutorial Series.

Happy Trailblazing..!!

Friday, 31 January 2020

Salesforce Integration Tutorial Part 11 - Test class for SOAP API Callout

Hello Trailblazers,

Welcome to the 11th tutorial of the Salesforce Integration Tutorial series. In the previous tutorial, we performed a callout to a SOAP API by importing a WSDL file in Salesforce. You can find that tutorial by clicking here. In this tutorial, we're mainly going to create a test class for the same callout that we performed before. So, make sure you've completed the previous tutorial before you begin with this one.

If you remember, in case of REST APIs, when we have to create a test class for an api callout, we used to create a mock class that implements HTTPCalloutMock interface and that mock class was used to create a mock response for the API callout that is going to initiate from our test class. In this case, we're going to do the same.

This time, we're going to create a mock class and implement a different interface which is known as WebServiceMock. This interface consists of a doInvoke() method which we need to override in our mock class. The doInvoke() method will receive request and response in the parameters and we can set the response parameter with the fake response that we're going to send for our soap api callout while running a test class.

If you remember, we named our auto-generated class for SOAP API callout as CalculatorService. So, let's name our mock callout class as:- CalculatorServiceMock. The code for the mock class is given below:-

As you can see above, our calculator service soap api basically peforms 4 mathematical operations:- Addition, Subtraction, Multiplication and Division. So, we've setup 4 macros named as:- ADD_MODE, SUB_MODE, MUL_MODE, DIV_MODE. These 4 macros basically define 4 modes in which our mock class will run to generate different responses when different methods of CalculatorService class are called. We've also declared another string variable named as mode which is setup using a constructor of this mock class.

Inside our doInvoke() method, we're checking the mode of our callout and setting up the fake response by using the responsewrapper provided by our auto-generated calculatorservice class.For ex:- When we have to generate a response for addition, we're using AddResponse_element response wrapper from CalculatorService class to setup the result of addition and finally setting up the response using the response map in which we have the key as:- response_x and the value as the instance of AddResponse_element class which is addResponse. Each response wrapper has a result variable like:- AddResult in case of addition and SubtractResult in case of subtraction where we can set the result of operation.

We've setup the result of operations accordingly by assuming that our input elements are:- 6 and 3. We'll be sending these numbers from our test class to the api callout so that we get the correct response from the mock.

Now, it's time to create our test class for SOAP API callout. We've created a test class with name:- CalculatorServiceTest. The code for the same is given below:-

As you can see above, first of all we've setup two integers as x and y with values 6 and 3 as we know that our mock class will send the correct response for any operation that we call using the soap api for these inputs. After that we've 4 test methods defined, one for each operation i.e.:- Addition, Subtraction, Multiplication and Division that can be performed by our CalculatorService class. So, we basically need to cover the Add(), Subtract(), Multiply() and Divide() methods which are defined in the CalculatorSoap inner class of our CalculatorService class that we were using to make callouts in our previous tutorial.

Let's have a look at testAddCallout() method. In this method, first of all we set the mock using our Test.setMock() method. This time we pass the instance of WebServiceMock.class in the first parameter and an instance of our CalculatorServiceMock class in the second parameter with the mode as CalculatorServiceMock.ADD_MODE in the constructor. Remember, ADD_MODE was one of the macros that were defined in our mock class and is used to check the mode in order to define the addition response. That's why we're passing the same variable in the constructor to setup the correct response for our additon SOAP callout.

After that, we simply created an instance of our CalculatorService.CalculatorSoap class named as calculator. We called the Add() method and passed our x and y variables with values:- 6 and 3. You can checkout the mock class again to see that we've setup the mock response as 9 in AddResult which is the sum of 6 and 3. We got the result from add method i.e. the actual api callout and that result is stored in result integer variable. We've also setup another variable expectedResult which is x+y. So, this expectedResult also has a value 9 and the result variable also receives 9 from our mock api. At last, we check that our expectedResult and result variables have same value using System.assertEquals() method and our test method for addition is complete.

Similarly, we've made different methods to cover subtraction, multiplication and division operations in our test class. You can run this test class and you'll see that the CalculatorService class is covered with 100% coverage as shown below:-



Congratulations..!! You've successfully created a test class for SOAP API callout with 100% coverage. All the code for this tutorial is present in our soapcallouttest branch of the SFDC-Integration-Tutorial github repository that can be accessed by clicking here. That's all for this tutorial, if you liked it, do share it in your network and let me know your feedback in the comments section down below.

Happy Trailblazing..!!

Saturday, 4 January 2020

Salesforce Integration Tutorial Part 10 - SOAP API Callout

Hello Trailblazers,

Welcome to the 10th tutorial of the Salesforce Integration Tutorial series. In the previous tutorials, we mainly worked on creating custom REST APIs and performing callouts to REST web services. In this tutorial, we're mainly going to perform a callout to SOAP API.

I am going to use the calculator SOAP API for this tutorial available at:- http://www.dneonline.com/calculator.asmx. The actual web service WSDL is available here:- http://www.dneonline.com/calculator.asmx?WSDL. However, Salesforce was not able to parse that WSDL.

Blog Update: Most of the people were not able to parse WSDL because of the same error i.e. more than one binding so I am specifying how I removed that error from the WSDL I am using.

I got the below error on importing the calculator WSDL in Salesforce.


It says:- Error: Failed to parse wsdl: Found more than one wsdl:binding. WSDL with multiple binding not supported

When I had a close look at the WSDL file, I got to know that it consists of multiple WSDL binding tags as shown below:-


So, I modified it a little bit i.e. removed the second binding tag and it's references from the WSDL. You can see the changes below:-

1. Removed the second WSDL binding.


2. Removed the binding references.



And that's it. My WSDL is now ready to be parsed by Salesforce and it was parsed succesfully without any errors and warnings. You can use the modified WSDL for this tutorial which you can see below:-

You can copy and paste the above xml in a new file or save it directly from here. Once you have the WSDL file ready, it's time to import that in Salesforce and call our Calcuator API from apex to perform some of the basic arithmetic operations. Salesforce has a built-in WSDL2Apex generator and we're going to use that only.

Importing WSDL to Salesforce using WSDL2Apex

In order to import WSDL to Salesforce, we're going to login into our Salesforce Org and follow the below steps:-

1. Go to Setup and search for Apex Classes and open the Apex Classes page.


2. You'll see that on the Apex Classes page, there is a button named Generate from WSDL which is used to import WSDL to Salesforce. Click on that button and you'll see the below screen.


3. Click on the Choose File button and select your WSDL file which is nothing but the same XML file that I described in the starting of the tutorial. WSDL mainly stands for Web Services Description Language. The WSDL file consits of the detailed description of SOAP Web Service which consists of the web service URL and the request/response formats for different operations that can be performed using the SOAP API. Here, I have saved the above XML in a file known as calculator.xml and have chosen that as shown below.


4. Click on the Parse WSDL button.You'll see the below screen.


5. You can change the Apex Class Name to anything you want, I am updating it to CalculatorService as shown below.

6. Click on Generate Apex Code button. It will automatically create the Apex Classes from the WSDL imported and you'll see the below screen which shows the names of two newly created apex classes in your org i.e. CalculatorService and AsyncCalculatorService:-


7. Click on Done. You'll see that two new apex classes are created in your org with the name:- CalculatorService and AsyncCalculatorService. For this tutorial we're going to focus on CalculatorService class. The code for the same is given below:-

As you can see in the auto-generated code above, there are a number of inner classes inside CalculatorService class. The main class on which we need to focus on is CalculatorSoap. This class contains 4 methods inside it namely:- Divide, Add, Multiply and Subtract. All these methods are taking two integers in the parameters and returning a single integer in the response after performing the operation. Inside each method, an API callout is made in which the parameters are passed, and the response returned from the API is the result of the operation which is returned from the method.

Now, let's have a look at the below code snippet and test our API by executing it in the Anonymous Apex window in the developer console.


As you can see above, I am simply creating an instance of the inner class inside our CalculatorService class and calling all the methods by passing two inputs x and y and debugging the result using System.debug(). As you execute the above code in the anonymous apex window, you'll see the below error:-


We haven't created the remote site setting for our endpoint yet and I haven't done it previously in the tutorial on purpose as it clearly shows us that salesforce is trying to reach out to the calculator api i.e. a SOAP callout is being made when we're executing this code. To add a Remote Site Setting, you can again go to setup and search for Remote Site Settings. You'll see the below screen on clicking on Remote Site Settings under Security Controls.


Click on New Remote Site button and create an entry for our endpoint dneonline.com as given below:-


Once you've created the remote site setting, go back to the anonymous apex window in the developer console and execute the code. I am providing you the code shown on the screenshot below so that you can copy it and use easily while learning:-

When you execute the above code, you'll see the output in the debug logs as given below:-


As you can see above, all the operations are performed successfully by our calculator api and we're able to get the correct results by making a SOAP callout request to the external system.

P.S.:- In case you receive an error like:- System.CalloutException: IO Exception: input contained no data please try executing it once again and it should work as it maybe some kind of issue with the webservice or WSDL but it works fine 95% of the time.

That's all for this tutorial. If you liked it, do share it with your network and make sure to let me know your feedback in the comments down below.

Happy Trailblazing..!!

Monday, 9 December 2019

Salesforce Integration Tutorial Part 9 - Test class for Apex REST Callout

Hello Trailblazers,

Welcome to the 9th tutorial of the Salesforce Integration Tutorial series. In the previous tutorial, we performed a callout to an external REST API and learned about the concept of wrapper classes and remote site settings. In this tutorial, we're going to create a test class for our api callout. I have made a small update in our SFDCStopCallout class in which I returned the response which I got from the API and updated the return type of getBlogs() method to HTTPResponse. You can have a look at the updated SFDCStopCallout class below:-

As shown above, we've the updated class and we're going to create a test class for this API callout. Let's begin.

Create a Mock Class

The first step is to create a mock class for API callout. The mock class is nothing but a class that will generate a fake response for our API callout in the test class. As, we don't need to hit the actual API while testing, we should have a fake response that will be returned when a callout is performed. I created a mock class for my SFDCStop Blogs API named as SFDCStopMock:-

As you can see above, the mock class is also a test class with @isTest annotation that implements HTTPCalloutMock interface. This interface consist of a single method respond() which accepts an instance of HttpRequest class as a parameter and return an instance of HttpResponse which we'll construct inside the method itself. So, we've overriden this respond() method inside which we initialized a new instance of HttpResponse named as response. Then we set the fake response body using the setBody() method and we also set the fake response header with key as Content-Type and value as application/json using the setHeader() method. Finally, we set the status code of 200 for the response using setStatusCode() method. At the end, we returned the fake response.

Test class for API Callout

Now, we have our mock API. So, we're ready to create a test class for our SFDCStopCallout class. I have created a new class named SFDCStopCalloutTest which is given below:-

As you can see in the above test class, I have created some constants that are given below along with their purpose:-

  1. RESPONSE_CODE :- This constant consist of the response code of the response coming from API callout.
  2. RESPONSE_HEADER_KEY :- This constant consist of the key in the response header from API callout.
  3. RESPONSE_HEADER_VALUE :- This constant consist of the value in the response header from API callout.
  4. RESPONSE_BODY :- This constant consist of the body of the response from API callout.

All these constants are used in test methods to verify the response coming from the api callouts in the assert methods. As you can see, I have created two test methods:- testGetBlogs and tesGetBlogsUsingFramework. As both the methods are covering the same getBlogs method of SFDCStopCallout class, we're going to have a look at the testGetBlogs method first which is the standard approach.

Inside this method, I have first setup the mock API using Test.setMock() method in which the first parameter is the interface type which is always:- HTTPCalloutMock.class and the second parameter is the object of our mock class. Therefore, I have passed it as new SFDCStopMock() as my mock class is SFDCStopMock which will return a correct fake response for this callout. In the next line, I am performing the API callout by calling the getBlogs() method from SFDCStopCallout class. This method is returning an instance of HTTPResponse that I am storing in a variable named response. Finally, I am verifying the response code, response header and the response body which is returned by our callout method by using System.assertEquals() method.

You'll get 100% coverage of the SFDCStopCallout class using this testGetBlogs() method alone. Now, one question to consider is:-

Do I need to create mock callout classes for each callout ?

The answer is YES. You need to create a mock for each callout you're perfoming in your apex to have full test coverage of that callout. However, you can use the same callout class by adding some conditions to provide different responses for different callouts. The easy solution to this problem is given in our second method which is testGetBlogsUsingFramework().

testGetBlogsUsingFramework() is making use of HTTPCalloutServiceMock class present in HTTPCalloutFramework to test this callout. HTTPCalloutFramework is a framework that simplifies HTTP Callouts in apex. You can install it from the GitHub repository in one click by clicking on the Deploy to Salesforce button. Click this link to go to the repository and click on the button to install the framework.

Now let's have a look at the second method that's using the framework. In this method, first of all I created an instance of HTTPCalloutServiceMock class named as sfdcStopApiMock. Then I set the response code, response header and the response body of my fake response by passing the constants as the parameters in the the setter methods available in the class. In the Test.setMock() method, I have passed the instance of HTTPCalloutServiceMock i.e. sfdcStopApiMock as the second parameter. The rest of the code is the same as in the first method. You can test the SFDCStopCallout class with this second method alone once you have installed the framework and it'll give you 100% coverage. So, we got to a conclusion that by using the framework,

"We are doing the same work performed by creating a separate mock class that is perfomed by writing 4 lines of code using HTTPCalloutFramework"

And the good thing is, you can reuse the same framework class again and again for different callouts. So, it's a great time saver for any developer. Similar is the case while calling out using the framework. If you want to have a detailed look on the framework you can view another blog post by clicking here.

That's all for this tutorial. If you liked it, make sure to share it among your network and let me know your feedback in the comments section below.

Happy Trailblazing..!!

Tuesday, 3 December 2019

HTTPCalloutFramework - A light weight framework for Apex HTTP Callouts

Hello Trailblazers,

I recently launched a new framework for simplifying apex HTTP callouts known as HTTPCalloutFramework. I open sourced it on GitHub and it's freely available now. In this post, I am going to talk about the functionality and advantages of this framework.

Overview

HTTPCalloutFramework helps you to simplify your apex HTTP callouts by storing all the metadata required for the callout as a record in a custom metadata named as:- HTTPCalloutConfiguration. This metadata stores the following essential information:-
  1. API Endpoint
  2. Request Method (GET/POST...)
  3. URL Parameters
  4. Header Parameters
  5. Request Body
  6. Request Timeout
This framework also includes two reusable mock classes that can be used while writing test classes for callouts:-
  1. HTTPCalloutServiceMock:- This mock class is used when there is a single callout within the code that's covered by the test method.
  2. HTTPCalloutServiceMultiMock:- This mock class is used when there are multiple callouts within the code that's covered by the test method.
These mock classes consists of constructors and methods that can be used to setup a mock response. For an example implementation you can have a look at HTTPCalloutServiceTest class that is used to cover the code in our service class.

Installation

To install this framework in your org, you need to go to the github repository here. Click on the Deploy to Salesforce button as shown below:-


As you click on that button, you'll be taken to a screen as shown below:-

Choose the correct environment and click on the Login to Salesforce button on the top right side. If you're using this tool for the first time, you'll see a screen asking for necessary permissions for deployment as below:-


Click on allow. You will see another screen as shown below:-


This screen is displaying all the metadata that will be deployed to your org. Click on the Deploy at the top right corner. Clicking on this button will deploy the framework to your org. You'll see the messages on the page on clicking deploy button as shown below:-


As you can see above, the deployment is successfully completed, in case there is an error, it'll be shown and the deployment will fail.

Congratulations..!! You have successfully installed HTTPCalloutFramework in your org

Usage

This metadata is mainly used in a service class known as HTTPCalloutService. While creating an instance of this class you can pass the developer name of custom metadata in the constructor and it will automatically fetch the data from HTTPCalloutConfiguration record and set it in the HTTP request.

Suppose, you need to add a request body yourself each time you're making a request as it's dynamic, you can do that easily by using the getter and setter methods in the service class. For ex:- For request body, we have setRequestBody() and getRequestBody() methods that can be used.

While using this framework You should only focus on the stuff that's dynamic while making a callout as the static data can be stored easily in the custom metadata and will be picked automatically by our service class.

Let's have a look at the example code and learn how by using this framework, we can reduce code. In this example, I am going to connect to another Salesforce Org - Playful Bear Org from my Salesforce Org - Curious Racoon Org and query contacts.

There are better ways to do this like:- Using named credentials etc. However, I am doing it solely by writing code for demo purposes.

So, if you want to connect to a different salesforce environment from apex you'll do something as shown below:-

As you can see above, I have simply created a wrapper for the token response in order to get the access token. The code in line no. 10 to 18 is used to hit the token URL and get the response from it. However, the code in line no. 20 to 26 is used to get the actual response by querying the contact from other org.

The other way around can be by using the HTTPCalloutFramework. Let's have a look at the below code:-

As you can see above, I can get the token very easily by using the code shown in line no. 10 to 11. I can query the contacts from other org and get the response from line no. 13 to 18. I have made two custom metadata records, one for authentication and other for querying as shown below:-



If I don't consider the wrapper, the total no. of lines of code a developer has to write without using the framework:- 16 and while using the framework its:- 8. So, we got to know that you can reduce your code to half along with the additional benifits like:- there will be minimal or no change in code in future as most of the details are stored in the custom metadata itself.

Not only this, if multiple developers are working on integrations to connect with the same systems, they can do the authentication stuff in just two lines of code which is common to all of them, there is no need to create a common method or anything like that. Also, for any change in the headers, or metadata we don't need to go to the code and change that you can simply do that in the custom metadata itself. Therefore, the advantages can be summarized as:-


  1. Lines of code are reduced.
  2. Request metadata can be updated without any change in code.
  3. Code reusability is implemented automatically.
  4. Data from static APIs can be fetched using two lines of code.
  5. Getter and setter methods make it easy for us to update the request before sending.
  6. Mock classes are available for handling single and multiple requests in the code covered by a test method while working on test classes.
  7. Named credentials support.

Even if you're using named credentials for the authentication part, it's easy to setup the request in the custom metadata. Let's have a look at the below code that's using named credentials for authentication and is making the same request:-


As you can see above, I have just given my metadata developer name in the constructor i.e. :- PlayfulBearQueryAPIWithNamedCredentials, updated the request URL with my query and displayed the response in debug. It's working fine. Now let's have a look at the custom metadata record for the same:-


You can see that I have specified the request method as GET and the request timeout in miliseconds. However, you can see that the request URL is:- http://callout:Playful_Bear_2/services/data/v47.0/query/?q=

As it's starting from callout: we got to know that it's using named credentials for authentication. The named credential record for playful bear org is given below:-


So, in this way, using both the named credentials and framework, I can even reduce my code more and perform my callouts more easily.

With this blog, I hope you got an idea of how can the HTTPCalloutFramework helps you in managing your REST callouts from Salesforce and how you can install and use it. There are two mock classes also present in the framework that I wanted to describe about but it'll be a very long post in that case. I recommend you to have a look at the test class for my service class here. In this test class, I have used both the mock classes:- HTTPCalloutServiceMock.cls and HTTPCalloutServiceMultiMock.cls for covering single and multiple callouts in the code covered by test methods. You can use these classes too while creating a test class as these are generic mocks. If you still need an example of using these mocks, let me know in the comments down below.

If you liked this framework, make sure to bookmark it on GitHub and show your support by clicking on the Star button present here. Also, share this post among your network and let me know your feedback in the comments section.

Happy Trailblazing..!!