SFDC Stop - Always the latest about Salesforce


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


Telegram logo   Join our Telegram Channel
Showing posts with label Apex Callouts. Show all posts
Showing posts with label Apex Callouts. Show all posts

Wednesday, 15 April 2020

100% Test code coverage for multiple dependent apex HTTP callouts without creating a mock class

Hello Trailblazers,

Welcome to the 5th tutorial in Simplifying the Callouts in Salesforce Tutorial Series. In this tutorial, we're going to Create a Test Class for Multiple Dependent Apex HTTP Callouts in a single transaction Without Creating a Mock Class. This is a Video-Only Tutorial Series. So, I am giving you a summary of the tutorial below and you can learn in detail by watching the video at the end of the blog.

Note:- This tutorial is using resources from previous tutorial. So, in case, you want to implement the same example on your own, make sure to have a look at the previous tutorial once.

Remember our OrgConnectService class from the previous tutorial ? In this tutorial, we're going to create a test class for that. Just to give a brief, our OrgConnectService class has a single method named:- createAccountAndContact() which is performing 3 dependent callouts using HTTPCalloutFramework. The first callout is responsible to create an Account in the connected org using standard API. The second callout will create a contact and link that contact with the account that was created in the previous callout and the third callout is going to query this contact and account from linked org. You can have a look at that class here.

Now, let's have a look at the test class below:-

As you can see above, we have 4 methods in this test class but we'll concentrate in detail on 1st method only as it's covering positive scenarios and is responsible for 76% code coverage. The rest of 3 methods are covering the negative scenarios and are similar. In createAccountAndContactTest() method, we're first of all Creating Individual Mocks for each callout that we're going to perform from the service class. Then, we created an instance of HTTPCalloutServiceMultiMock named as:- multiMock and we added all 3 individual mocks to this multi-mock using addCalloutMock() method.

This method takes the endpoint URL as the first parameter and the individual mock in the second parameter. To set the endpoint URL properly, we created an instance of HTTPCalloutService class named as destinationOrgService by passing the custom metadata name in constructor as we've done in previous tutorials. Finally, we set the multi mock using our Test.setMock() method in which we passed HTTPCalloutMock.class in the first parameter which is the type and in the second parameter we passed our multiMock instance.

Then we simply called our createAccountAndContact() method and passed the required parameters and it automatically used our multi mock setup to get the fake responses that we've set in individual mocks according to the URL it is hitting. Finally, we checked the returnValueMap we're getting from the method to make sure that the callout is successful.

Let's discuss one method with a negative scenario too. In createAccountAndContactTestWrongResponseAccount() method, you can see that I intentionally passed the QUERY_SUCCESS_CODE in the mock just because I want to cover the scenario when my response code from account callout is not 201. As I am testing negative scenario for first request now, I don't need to create a multi mock because I'll be getting a response code as 200 (set using QUERY_SUCCESS_CODE) during test run (first callout for account creation where expected response code is 201) and it'll return an error without executing further code.

In another method createAccountAndContactTestWrongResponseContact(), I am checking negative scenario for second callout. Because of this, I created a multi-mock where in accountMock I passed in CREATE_SUCCESS_CODE as I want this request to be successful. Whereas, in contactMock I passed in QUERY_SUCCESS_CODE as I want this request to be failed and finally asserted the ERROR_CODE and CONTACT_ERROR_MESSAGE for this request.

Want to learn in depth ? Have a look at the below video:-



In this tutorial, we learned how we can get 100% code coverage for multiple dependent apex HTTP callouts without creating a mock class as shown below:-


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..!!

Friday, 10 April 2020

Multiple Dependent Apex HTTP Callouts in a Single Transaction from Salesforce | HTTPCalloutFramework

Hello Trailblazers,

Welcome to the 4th tutorial in Simplifying the Callouts in Salesforce Tutorial Series. In this tutorial, we're going to perform Multiple Dependent Apex HTTP Callouts in a single transaction. This is a Video-Only Tutorial Series. So, I am giving you a summary of the tutorial below and you can learn in detail by watching the video at the end of the blog.

Note:- This tutorial is using resources from previous tutorial. So, in case, you want to implement the same example on your own, make sure to have a look at the previous tutorial once.

We've made some updates to our CustomerRubyOrg metadata record as shown below:-


As you can see above, I have added a header with key:- Content-Type and value:- application/json. I have updated the method as POST and also the endpoint as:- callout:CustomerRubyAPI/services/data/v48.0 where I am referring CustomerRubyAPI which is the name of my Named Credential record that we created in our previous tutorial.

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


As you can see above, we have a OrgConnectService class. In which we have a single method named as createAccountAndContact(). This method is receiving a string for account name and a contact object as a parameter. Inside this method, we're performing 3 callouts to another salesforce org (we call it as source org) one by one. So, in total 3 operations are performed in source org as shown below:-
  1. Creating a new Account Record using the account name received in parameter.
  2. Updating the contact record received in parameter by linking it with Account Record and creating a new Contact Record.
  3. Querying the contact and related account record.

First of all we're creating an instance of HTTPCalloutService named as destinationOrgService and we passed the custom metadata name:- CustomerRubyOrg in the constructor. Then we're setting the endpoint URL and request body for the callout using getter and setter methods present in HTTPCalloutService which is a part of HTTPCalloutFramework.

Finally, we're sending the request and checking if the response code is correct or not. For record creation in salesforce, the response code should be 201 and for querying it should be 200. For the first two callouts, I am parsing the response body using JSON.deserializeUntyped() method which is returning an Object in the response that I am typecasting into Map<String, Object>. I am checking the value of success and getting the id of the record which is created. However, in the third callout, I am simply displaying the response using System.debug().

Wether the request is successful or not, we're forming a Map<String, String> which we're returning by this method. We'll be using this map in the next tutorial where we'll be creating a test class for this class in order to add asserts for all 3 callouts depending upon the return value map.

I have added necessary comments to help you understand the code. The basic flow is :- We're creating an account record by calling out to salesforce standard api. Then we're creating a contact record and linking it with the account record whose id we got in the response from first API callout. Finally, we're querying the contact and related account record using the contact id that we got in the response from 2nd callout. So, in this way each callout depends on the previous callout response which is a very common requirement that we get usually face in real life projects while working on integration.

Want to learn in depth ? Have a look at the below video:-



In the next tutorial we'll see how we can create a test class for such a scenario where we have 3 dependent callouts in a single transaction and that too without creating a mock class using HTTPCalloutFramework. 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..!!

Tuesday, 7 April 2020

Connect two salesforce orgs using Named Credentials, Authentication Provider & HTTPCalloutFramework

Hello Trailblazers,

Welcome to the 3rd tutorial in Simplifying the Callouts in Salesforce Tutorial Series. In this tutorial we're going to connect two salesforce orgs thereby learning the concept of Named Credentials, Authentication Provider and HTTPCalloutFramework in detail. As this is a Video-Only tutorial series. I am giving you a brief of what we've done in this tutorial below, and you can have a detailed look in the related video. So, let's begin.

As we're going to connect two orgs that means, we'll be fetching some data from one org to another. Let's call the org from which we're going to fetch data as the Source Org and let's call the org which is pulling the data from source org as the Destination Org.

Connected App in Source Org

The first step is to create a connected app at the third party which is responsible for providing data. In this case, our third party is our Source Org. So, we need to create a connected app in our source org as shown below:-


Notice that we have selected two OAuth scopes here:-

  1. Access and manage your data (api) :- Used to query data from Salesforce
  2. Perform requests on your behalf at any time (refresh_token, offline_access) :- Used to maintain the refresh token which will be used by authentication provider in order to get new access token automatically when refresh token expire.
We'll be using the Consumer Key and Consumer Secret from this connected app in our authentication provider.

Authentication Provider in Destination Org

We have created an authentication provider record in destination org as shown below:-

Points to notice here:-
  1. Provider type is Salesforce as we're going to connect to a Salesforce Org.
  2. Consumer Key and Consumer Secret are copied and pasted from our connected app which is made in another salesforce org as shown above.
  3. Callback URL is automatically generated when you save the record of your authentication provider. We need to copy and paste this callback url in our connected app which was created in the source org and update that connected app (You can see above that our connected app is having the same Callback URL which is given by our authentication provider). I've updated it later.

Named Credential in Destination Org

We created a named credential in the destination org which is using our authentication provider.

Please make sure that the URL is the base URL of the source org which is visible in Salesforce classic mode as shown in the above image. As you can see, the Identity Type for named credential record is Named Principal and the authentication provider that we created before is selected here. When you save this record for the first time, you'll be taken to a login page where you have to login with the credentials of "Source Org" i.e. the org where you've created your connected app. Make sure that the authentication status is updated to Authenticated as <source org username> as shown in the above image.

HTTPCalloutFramework in Destination Org

Please make sure that you've installed HTTPCalloutFramework in your destination org. You can install it from here. Once you have it installed in your org, you can create a custom metadata record of HTTPCalloutConfiguration as shown below:-

We've set the endpoint as:- callout:CustomerRubyAPI/services/data/v48.0/query/ where CustomerRubyAPI is the name of my named credential. As, I am going to query some records from my source org, so I have setup that URL as the endpoint here. In the URL parameters, I have:- q:<query> therefore, I'll update the URL parameter with key q and set it's value to my actual query before calling out and the final URL will be similar to this:- callout:CustomerRubyAPI/services/data/v48.0/query/?q=SELECT+Name+FROM+Account.

Fetching Data from Source Salesforce Org to Destination Salesforce Org


You can have a look at the above code which is used to perform any query in source org and get the results as the response of the API. You can see in the debug behind which shows the result of a query on account. However, you can perform any query and you don't have to worry about authentication as it's being handled by Named Credentials and Authentication Provider. All other configurations are handled by the HTTPCalloutFramework.

Note:- Here we can easily add any dynamic query because it's handled in the URL parameters. But in case you need to add any dynamic value in the request body let's say, I would recommend to have the format in the HTTPCalloutConfiguration record and use string replace and getters/setters to update the request body before callout.

If you want to have a detailed look, you can watch the video below:-



That's all for this tutorial. In the next tutorial, we'll have a look at how we can create a test class to manage multiple callouts in single transaction. Our test class will be having 100% code coverage and that too without creating a mock class. So, stay tuned.

Happy Trailblazing..!!

Saturday, 4 April 2020

100% code coverage for apex HTTP Callout in Salesforce without creating a mock class

Hello Trailblazers,

This is the second tutorial in Simplifying the Callouts in Salesforce Tutorial Series. In this tutorial we created a new class named as SFDCStopService which is responsible to perforn a callout to SFDCStop Blogs API :- https://sfdcstop.herokuapp.com/blogs 

You can have a look at the SFDCStopService class below:-


For this class, we created a test class so that we can cover the code and we were able to achieve 100% code coverage without creating a mock class using HTTPCalloutFramework. Let's have a look at the test class below:-


So, the question is How we're able to achieve 100% code coverage without creating a mock class ? The answer to this question is that HTTPCalloutFramework provides you an in-built mock class named as:- HTTPCalloutServiceMock. You can create an instance of that and in the mock class constructor you just need to pass the fake response code and the response body. That's it our in-built mock class will create a fake response for you when you're calling out during test.



As, this is a Video-Only Tutorial Series, In case you want to know in detail, you can have a look at the related video below:-



Do give this framework a try and let me know your feedback in the comments down below. You can find all the related code in the singlecallouttest branch of my HTTPCalloutFramework Tutorial Series github repository here. In the next tutorial, we're going to connect two salesforce orgs very easily and will fetch data from one salesforce org to another using HTTPCalloutFramework.

Happy Trailblazing..!!

Thursday, 2 April 2020

Introduction and Installation of HTTPCalloutFramework

Hello Trailblazers,

About 4 months ago, I created a new framework to simplify HTTP Callouts in Salesforce. I made it free, open sourced it on GitHub and shared the same with my #SalesforceOhana i.e. YOU. I got valuable feedback from some of you for which you can see the comments on the post below:-



Thanks to everyone who gave their suggestions on the above post. I improved the framework and recently had a webinar on this. At that time, I decided to create a small tutorial series on this instead of a webinar because there is so much to tell about this framework which can't be covered in one webinar. ( Thanks Radhika Bansal for your suggestion 😊 )

So, here I present the first tutorial in Simplifying the Callouts Tutorial Series by SFDCStop. In this tutorial we're going to have a brief look at HTTPCalloutFramework which is a free and open source solution to simplify apex HTTP Callouts in Salesforce. This is going to be a Video - Only Tutorial Series and I am going to cover everything up in about 6 or 7 tutorials at max (estimated). I am going to share all the resources (presentation/code/videos) in the blogs that I am going to publish under this tutorial series.

For the first tutorial, we have a presentation featuring Why do we need this framework ? What's the current scenario that we're dealing with ? and how does it help you to simplify the callout implementation.

Also we're going to cover the following stuff:-
  1. Installation of HTTPCalloutFramework
  2. Configuring the framework in your org
  3. We're going to perform a callout using 2 LINES OF CODE to a static SFDC Stop Blogs API:- https://sfdcstop.herokuapp.com/blogs 

    YES..!! You read it right...!! We can perform a callout in only 2 lines of code using this framework

To know more, have a brief look at the presentation below:-



And here is a video featuring HTTPCalloutFramework:-



If you liked this tutorial, make sure to give a try to HTTPCalloutFramework and let me know your feedback in the comments section below. You can also contribute to the framework by sending a pull request on github.

Happy Trailblazing..!!