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

Thursday, 21 November 2019

Salesforce Integration Tutorial Part 7 - Creating a test class for Apex Web Service

Hello Trailblazers,

From part 1 to 6 in the Salesforce Integration Tutorial Series, we created custom APIs in salesforce and also learned about the various annotations for different HTTP methods including:- GET, POST, DELETE, PUT and PATCH method.

In this tutorial, you'll learn, how we can create a test class for an apex web service. I have added all the methods together in my ContactResource class available in the master branch of my github repository. You can have a look at the same here.

I created a test class for this ContactResource class named ContactResourceTest which is given below:-

As you can see above, I have a total of 7 methods in the above test class out of which I'll be explaining about:- testGetContactIdAndNames, testCreateNewContact and testUpdateContact. Rest of the methods are similar to these and if you're still not able to understand any of those, let me know in the comments. Let's begin.

makeData()

Before moving onto our methods, I just want you to brief about the makeData() method which is doing nothing but inserting a new contact with name:- Richard Hendricks. This method will be called automatically before all the other methods when the test class is executed because it's annotated with @TestSetup annotation. The test setup method is mainly used to create data which is required by the test class so that the test class can run properly.

testGetContactIdAndNames()

In this method, first of all I have created an instance of RestRequest class named:- contactRequest. I have setup the requestUri to the actual URL of my salesforce instance that I am going to hit. This URL consists of 1 at the end as you know that in my GET request to the /ContactAPI/, I need to specify the number of contacts I am going to fetch at the end of URL, so, I have specified it as 1. Then, I've setup the HTTP method as GET in the request as my actual class method getContactIdAndNames() has an @HTTPGet annotation. I have finally assigned this contactRequest to the request variable of RestContext class to set the input request before calling the actual method. Then, I called the getContactIdAndNames() method from the ContactResource class which returned a list of contacts in the response that I stored in returnedContacts variable. Finally, I am confirming the reponse by checking that the returnedContacts list is not null, has a single contact that I inserted in the makeData() method and has the same name that I gave it to during the insertion of the contact.

testCreateNewContact()

In this method, we're simply calling the createNewContact() method from the ContactResource class. This will work as we're able to pass the required data through the method parameters and we've not checked anything else (For ex:- HTTP method of request, URL etc.) in the actual method. So, we don't need to setup a rest request to test this method. As we know, our createNewContact method will create a new contact. Therefore, I'll query the newly created contact by using the id from the contact which is returned by our method. For confirmation, I'll check that the returned contact is not null and has a valid id, as well as I'll check that the newly created contact is not null and has the same lead source which was in the returned contact.

testUpdateContact()

In this method, first of all I have queried a single contact to get the id of the contact which is already inserted. Then, I have created a new instance of Contact and set it's first name. We're going to send this contact in the request body and will update our existing contact's first name. Next, I created a new instance of RestRequest and setup the httpMethod as PATCH and the requestUri with the proper value. You can see that I have added the queried contact's id at the end of request uri as if you remember our updateContact() method, it'll get the id of the contact to be updated from the URL and the new contact parameters from the request body and will then update the contact and return the same in the response. Next, I've set the requestBody variable of contactRequest. It should have the type as BLOB, so, I have converted my contact object into JSON using JSON.serialize() and then converted the JSON string to blob using Blob.valueOf(). I have set this contactRequest to the RestContext.request so that my request is setup properly. Then, I called my updateContact() method from my ContactResource class and queried the contact again with the contact id that I got in the initial query.
Finally, I checked that the returned contact in the response and the queried contact have the same id. I also checked that the first name is updated to the new value according to my request body and the last name is the same as before.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



So, in this tutorial, you learned how you can create a test class for apex web services, setup HTTP request context variable using RestRequest class and also calling the method directly by passing the parameters if it's not necessary to setup request.

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

Happy Trailblazing..!!

Wednesday, 13 November 2019

Salesforce Integration Tutorial Part 6 - Exploring PATCH Method

Hello Trailblazers,

Welcome to the 6th Tutorial in the Salesforce Integration Tutorial Series. In the previous tutorial, we learned about PUT method in detail. You can have a look at that tutorial by clicking here. In this tutorial, we'll have a look at the PATCH method in detail. We'll be creating a custom REST API that will interact with the contact object which is already present in Salesforce.

The PATCH method is mainly used to update fields in existing records. Therefore, it'll be associated with an update operation. So, we can send all the fields with the values in the request body which we need to udpate. Make sure you send the record id in this case, as we need to identify the record we want to update.

In this tutorial, we'll modify our code in the ContactResource class which has a URL mapping of /ContactAPI/* and will be updating the method annotation to @HTTPPatch and the method name to updateContact. Let's have a look at the below code:-

As you can see above, first of all, we are getting the request and assigning it to an instance of RestRequest class which is contactRequest. Then we got the requestURI from the contactRequest and using this, we're getting the Id of contact which is passed in the URL by getting the substring after last slash (/) from the requestURI. The contact id is assigned to the contactId variable. We're also getting the request body from the contactRequest and assigning it to the requestBody variable by converting it to String using the toString() method.

After that, we need to create an instance of Contact object that we're going to pass in the update operation. If the contactId string is not empty, we'll proceed further otherwise, we'll directly return the contact instance having null value. Inside the if we're deserializing the JSON using the JSON.deserialize() in which we pass the requestBody as the first parameter and the predefined Contact class as the second parameter which will be used to map the fields in order to deserialize. Then we assigned the contact id to the contact object using the contactId variable and finally, we performed the update operation on the contact. The updated contact is returned in the response in this case.

I created a record in Salesforce and tested this API from workbench.


As you can see above, this contact has a lead source of Phone Enquiry which I am going to update using workbench.



I've selected the PATCH method from the radio buttons, specified the record id in the URL after the last slash (/) and in the request body, I've just specified the data I want to update i.e. leadSource. I executed the request and got the updated contact object in the response showing the lead source as web. You can see above that the record id in the response is the same that we passed in the URL. I checked the same record in my Salesforce Org which is shown below:-


As you can see above, the lead source is updated to Web. Remember in the code, if we don't pass a contact id, the un-initialized contact instance will be returned in the response which has a value of NULL. I tried calling out the API without a contact id and got the below response:-


As you can see above, the API has returned a blank response, therefore it's even not formatted and nothing is shown in the raw response as well because our API returned NULL in the response body.

What if I want to update multiple contacts at once ?

In this case we need to take the similar approach like we did in case of DELETE method. Let's have a look at the below code of ContactResource1 class which has a URL mapping of /ContactAPI1/*

As you can see above, Everything is same like we did previously in case of delete, I have created the same wrapper class named as ResponseWrapper. I've updated the method name to updateContacts which is returning the list of ResponseWrapper in the response. Inside the method, we initialized a list of ResponseWrapper named as responseWrapperList. Then we again, got the input request in the instance of RestRequest class and parsed the request body as a String. Then we initialize a list of contacts named as contactsToUpdate which is assigned the deserialized input JSON. Using the List<Contact>.class as the apex type which is passed as a second parameter in the JSON.deserialize() method, this apex type is mainly the type of object that the method will create after deserializing the JSON input. In our case it's List<Contact> as we'll be sending the contact list in the input request body.

Once, We have the list of contacts to update, we use the Database.update() method with the allOrNone parameter (2nd parameter) as false to allow updation of valid records in the list. We got the results of the list update in the form of an array of Database.SaveResult. We've iterated the updateResults and created a response wrapper for each update call with the correct data (success or error messages) accordingly and added it to our responseWrapperList before ending the loop. Finally, we returned the responseWrapperList in the response.

I tested this API using workbench and used a list of two records in the input request body. The first record has other data but it's without an id so it should fail in an update operation whereas the second record is the one with the name Russ Hanneman that we created previously, I updated it's name to Richard Hendricks. After calling the API, I got the below results:-


As you can see in the response, the first record cannot be updated as specified in the error message that id is not specified in an update call. Whereas, the second record is updated with the same record id returned that we passed in the input JSON. I also checked in salesforce, and the record was updated there also as shown below:-


Tired of reading or just scrolled down, don't worry, you can watch the video too.



That's all for this tutorial, in the next tutorial, we'll be talking about creating test classes for a webservice class similar to those we created till now. All the code used in this tutorial is available in the patch branch of my github repository that you can access by clicking here. If you liked this tutorial, make sure to share it and let me know your feedback in the comments below.

Happy Trailblazing..!!

Thursday, 7 November 2019

Salesforce Integration Tutorial Part 5 - Exploring PUT Method

Hello Trailblazers,

Welcome to the 5th tutorial in the Salesforce Integration Tutorial Series. In the previous tutorial, we learned about DELETE method in detail. You can view that tutorial by clicking here. In this tutorial, we'll have a look at the PUT method. We'll create a custom REST API which will deal with the contact object that is available in salesforce.

 The PUT method gives us the flexibility by updating a record if it's already present in Salesforce. In case, the record is not present, it'll create a new record. We know that when we have to create/update a record in Salesforce we use the upsert call. In that case, if a record id is specified in the object instance we're trying to upsert, it'll update that record. However, in case a record id is not present in that instance, it'll create a new record. Therefore, we'll be using upsert in our PUT method.

The PUT method will have an annotation of @HTTPPut. It supports a request body so there are different ways you can pass data to this method. One way can be to pass all the data in the request body which is automatically mapped to the parameters of the method. Another way can be to deserialize the JSON in the request body in the method itself and cast it to the object you want to upsert, in our example it'll be contact. We've seen both the approaches in our previous tutorial in which we've explored the POST method in detail. So, here we'll be going with something different.

We'll pass the record id at the end of the URL and all the other parameters in the request body which will be mapped to the method parameters (to keep it simple). If a record id is present at the end of the URL, our upsert call will update that particular record, otherwise it'll create a new record. We'll be using the same ContactResource class and updating that. Let's have a look at the updated code below:-

As you can see above, in our ContactResource class which has a URL Mapping of /ContactAPI/*, we have a method named as upsertContact which is having 4 parameters namely:- firstName, lastName, birthDate and leadSource as we had in out POST method tutorial. Inside this method, we're getting the actual request using the request context variable from the RestContext class and assigning it to an instance of RestRequest class named contactRequest. Then, we're getting the requestURI from contactRequest and finding the contact id from that request URI by getting the substring after the last slash (/) from the request URI. We then assign the contact id to a String named contactId. Now, we have all the values, so it's time to create a new contact and upsert it.

Next, we created a new instance of contact and checked if the contactId string is not empty, we assigned contactId as the id of the contact we're going to upsert. I noticed one thing here that it's not necessary to use Id.valueOf() like we've done previously as Salesforce automatically typecast it to the Id type. Then we'll assign the first name, last name, birth date and lead source for a contact. We're parsing the birthdate using Date.parse() and converting the string input into date format. If you don't want to parse the date, you can directly have a parameter of type Date in the method itself as:- Date birthDate but you need to take care of the format in that case in which you're sending date. The acceptable format for that is:- YYYY-MM-DD. Finally, we're upserting the contact and returning the contact in the response.

I tested this API from workbench and got the following results:-

Inserting a New Contact

You can see that PUT is selected from the radio buttons above and a new contact is created in Salesforce with the data given:-


Updating the same contact by specifying an id in the URL


You can see in the response, we got the same id back that we mentioned in the URL and the contact's lead source is updated in Salesforce from Web to Phone Inquiry as shown below:-


[UPDATE]:- The below case is valid only because I am taking the input in the form of method parameters and I am overriding the contact values with the values passed in method parameters. Therefore, the values are updated to null if it's not present in the input. In case, you're parsing the whole JSON request body by using requestBody variable of RestRequest class, the system will consider only the values present in the input and will update/insert only those. Rest of the data remains unaffected if upsert is updating the record which is already present.

If you notice, you'll see that even if I have to update one single field, I am passing all the other values in the input too. That's because, upsert method expects the field values to be present while upserting a record. To confirm that, let's try to update the lead source to web again, but this time we'll pass only the changed value in input. You'll see the below response:-

It is giving us the error that the required fields are missing even if I am specifying the record id in the URL and as we know, this record also have a value in the last name. Let's just fill up the last name and see what happens.


As you can see above, I have updated the last name to Hendricks and also the leadSource back to Web and I got the response in which the first name and birth date is specified as null. Let's have a look at the record in Salesforce.


You can see above that the last name is updated to Hendricks and the lead source is updated to Web. However, the birth date and first name are shown as empty as they're automatically updated to null as shown in the response. So, while using PUT method, we need to take care that we pass the whole record as it'll be an upsert call.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



That's all for this tutorial, in the next tutorial we'll have a look at the PATCH method in detail which is specifically used to update the record fields. You can find all the code related to this tutorial in the put branch of my github repository here. If you liked this tutorial, make sure to share it in your network and provide your feedback in the comments below.

Happy Trailblazing..!!

SFDC Stop is now among Top 75 Salesforce Developer Blogs

Hello Trailblazers,

I am so happy to share with you all that SFDC Stop is now ranked at No. 26 in "Top 75 Salesforce Developer Blogs & Websites To Follow in 2019" by FeedspotThis is what feedspot has to say about the list:-

"The Best Salesforce Developer blogs from thousands of Developer blogs in our index using search and social metrics. We’ve carefully selected these websites because they are actively working to educate, inspire, and empower their readers with frequent updates and high-quality information."

The blogs are ranked on the following metrics:-

  1. Google reputation and Google search ranking
  2. Influence and popularity on Facebook, twitter and other social media sites
  3. Quality and consistency of posts.
  4. Feedspot’s editorial team and expert review

I am honoured to have SFDC Stop be a part of this list and wanted to personally thank each and every one of you who has ever been a part of #SFDCStopOhana. This is what we have achieved together..!!


You can have a look at the full list by clicking here.

Thank you once again and keep supporting SFDC Stop.

Best Regards,
Rahul

Tuesday, 5 November 2019

Salesforce Integration Tutorial Part 4 - Exploring DELETE Method

Hello Trailblazers,

Welcome to the 4th tutorial in the Salesforce Integration Tutorial Series. In the previous tutorial we learned about the POST method in detail. You can have a look at the same by clicking here. In this tutorial, we'll be working with the DELETE method, creating a custom REST API and will be working with Contact object which is already present in Salesforce.

The DELETE method in HTTP is mainly used to delete one or more records. We'll modify our existing code and have a look at the deletion of records using the method with @HTTPDelete annotation. The delete request usually don't have a request body and receive the parameters in the URL itself. In most cases, we pass the record id in the URL and that record id is used to delete the record in the system.

To begin, let's have a look at the below code:-

As you can see above, In my ContactResource class, I have updated the method name to deleteContact which is returning a Map<String, String> in the response and is having an annotation of @HTTPDelete. Inside this method, I have initialized a Map<String, String> which has a name responseMap. After that, I have initialized my RestRequest instance named contactRequest with the request context variable of RestContext class. Therefore, I have my actual request now assigned to the contactRequest variable.

As, I am deleting the contact here, I'll be adding a contact id to the end of the URL. The contact id will be used to delete the respective contact. So, next I am getting the requestURI from the contactRequest and then getting the Id of the contact by getting the substring after the last slash (/) in the URI and converting it to the Id format by passing it into Id.valueOf() method. Now, as I got the contact id of the contact to delete. I am initializing a new Contact with this id.

At the end, I have a try-catch block. In the try block, I am trying to delete the contact. If the contact is deleted, I am adding two key-value pairs in the responseMap i.e. success with value 1 and message with value Record Deleted Successfully. In case of an exception, I am capturing the DmlException in the catch block. In that case, I am again adding two key-value pairs in the responseMap but here success will have a value 0 and message will have a value ex.getMessage() which will return the error message from the exception as a string, as ex is the instance of our DmlException class. Finally, I am returning the responseMap in the response.

I tried calling this API from workbench by passing a valid contact id and got the response below:-

As you can see above, I have selected DELETE from the radio buttons and passed the contact id of the contact I wanted to delete and I am getting the proper response with a success value of 1 and message value as:- Record Deleted Successfully. Now, if I try to call the same API with the same input again, I am getting the below response:-

As you can see above,  this time, I am having a success value as 0 and message consits of the actual error message. You can see that this is a DML exception as I am trying to delete a record which is already deleted. You can also have a look at the raw response which will be in the proper JSON format as shown below:-

What if I want to delete multiple records ?

In this case, either you can use URL parameters about which we have learned earlier in the GET method tutorial. You can view that tutorial by clicking here. However, I am going to use the same approach as we're already using and I am going to add comma , separated contact ids at the end of the URL like:- /services/apexrest/ContactAPI1/0037F00001hw4nG,0037F00001hw5lB,.....

Let's have a look at the below code of ContactResource1 class having the urlMapping as:- /ContactAPI1/* 


As you can see above, this time I have created a new wrapper class with a global identifier named as ResponseWrapper which has two String variables:- success and message. After that, I have created an @HTTPDelete method named as deleteContacts which will return the list of my ResponseWrapper in the response. I'll get the list of ResponseWrapper in response and I'll be able to check for each contact, whether it was deleted or not.

In this method, first I've initialized a List<ResponseWrapper> named responseWrapperList. I have again got the contactRequest and the contactRequestURI same as previous but this time, I am splitting the substring after slash (/) from the URI using a comma (,) and getting the array of contactIds in return. So, my URL will be like:- /services/apexrest/ContactAPI1/0037F00001hw4nG,0037F00001hw5lB,.... I can have multiple contact ids of the contacts I want to delete after the ending /. I'll take that substring and split it using a , and I'll get the contact ids in a string array named contactIds. After that, I have initialized a new list of contact named contactsToDelete and I have a for loop running over my contact ids inside which I am creating an instance of contact for each id and adding it to the contactsToDelete list.

Now, I want to make partial deletion possible, i.e. if I am sending 10 contacts for deletion and 5 can be deleted while 5 cannot, salesforce will delete those 5 which can be deleted easily. For this, I am using the Database.delete() method which is taking the list of contacts to delete as the first parameter and it's second parameter represents allOrNone which is a boolean variable. If allOrNone is true, either all the contacts will be deleted or none of them. On the other hand, if allOrNone is false, deletion of some contacts in the list is possible even when others cannot be deleted. The Database.delete() returns an array of Database.DeleteResult which is named as:- deleteResults which can tell us the status of the delete operation for every contact.

At last, I am iterating these deleteResults and for each iteration, I am creating a new instance of ResponseWrapper by the name wrapper. Then I am checking for each contact whether the operation was successful by isSuccess() method. If the operation was successful, I am setting up the success and message variables in the wrapper for that contact with appropriate values and in case, the operation was not successful, I am getting the errors using deleteResult.getErrors() which will return a list of Database.Error class that I am iterating in a for loop by assigning one instance of Database.Error at a time by the name error. I am forming the proper error message using methods from the Database.Error class like:- getStatusCode(), getMessage() and getFields(). Finally, I am adding this wrapper to the responseWrapperList and returning this list as a response.

I tested this API in workbench with one valid contact id and another id of a contact which was already deleted. I got the below response:-

As you can see above, I was able to delete one contact while other contact cannot be deleted as the id was not valid. I got two different responses in a list which was returned to me in the response. If you check the raw response, it'll show you the proper JSON format as below:-


That's all for this tutorial. In the next tutorial, we'll explore the PUT method in detail.The whole code of this tutorial is available in the delete branch of my SFDC-Integration-Tutorial github repository which can be viewed by clicking here.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



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

Happy Trailblazing..!!

Salesforce Integration Tutorial Part 3 - Exploring POST Method

Hello Trailblazers,

This is the third tutorial in the Salesforce Integraton Tutorial Series. In the previous tutorial, we explored the GET method, created two APIs and tested them using workbench. You can have a look at the same by clicking here. In this tutorial, we will explore the POST method in detail. Throughout the whole series, we're going to work with the predefined Contact object and will be performing operations on this using the custom REST APIs.

The POST method is mainly used to create new data and has an annotation of @HTTPPost. In our case, we're going to create a contact by defining a new method in our ContactResource class by the name of createNewContact. Let's have a look at the below code:-


As you can see above, in place of GET method, I have a POST method called createNewContact in my ContactResource class i.e. a method with @HTTPPost annotation. This method has a return type of Contact as we're going to return newly created Contact in the response for confirmation. This method is taking four parameters in the input:- firstName, lastName, birthDate and leadSource.

Inside this method, I simply created a new instance of the Contact object. Then I assigned the contact's FirstName, LastName, Birthdate and LeadSource, their respective values using my input parameters. As the birthdate is of date type, so, I parsed it using the parse() method of predefined Date class. Finally, I inserted the contact and returned it in the response.

If you test this API from workbench, you'll see the below output:-

As you can see above, I have selected the method as POST among the radio buttons and in the request body, I have added the below JSON:-

{
  "firstName": "Richard",
  "lastName": "Hendricks",
  "birthDate": "08/03/1989",
  "leadSource": "Web"
}

The 4 keys in the JSON object above represent the 4 parameters of my createNewContact method. Therefore, the values that I pass in here are automatically mapped to the respective parameters using the keys. Make sure that the keys have the same name as the name of the parameter in your method.

In the response, you can see that I have a JSON object which consists of all the parameters I've sent along with the record Id. Using this, I can verify that my record is inserted successfully. I can also have a look at the raw response which is as given below:-


On having a closer look at the response, you can see that the response JSON object consists of keys which are nothing but the actual API names of fields in the contact object. It is showing me the contact record which is created in Salesforce along with the id of the record. You can use the id to check the record in your org and you'll see that the record is created successfully.


Congratulations..!! You've created a record using your own custom API in Salesforce. Now the question arises:-

What is the maximum number of parameters that I can add to a POST method ?

We've added 4 parameters currently to our post method which are used to create a new record. But, what if I have to create a record which have 50 fields ? In that case, I need to pass the value of all the 50 fields to the API. Should I create a method with 50 parameters ? Is that allowed ?

Well, I have tried that thing long ago and I didn't remember exactly but I think Salesforce will not allow you to create a method with more than 15-20 parameters. So, we need to think of a different solution. Now, we know that all the values are coming to our API in JSON format through our request body. This means that, if I can access the request body, I can extract the value of each field from the request body itself. Let's have a look at the below code of a different class named ContactResource1 which have a URL mapping of /ContactAPI1/*:-


If you see above, I have initialized the instance of RestRequest class which is contactRequest. Then I got the requestbody from the request by using the requestBody variable of RestRequest class. I have converted the request body to string using toString() method as the request body is originally in BLOB format and assigned it to a String called requestBody. Then, as we know that the request body is in the form of JSON, so, I deserialized the JSON request string into an object using JSON.deserialize(). JSON.deserialize() method takes the JSON string in the first parameter and the wrapper class in the second parameter. In this case my wrapper class is the predefined Contact.class of salesforce. It returns an object so I have to cast it to an instance of Contact using (Contact) before the JSON.deserialize() method. Finally, I have the contact object that I am inserting and returning in the response.

I have tested this API in workbench and got the below result:-

As you see above, I can add as many fields as I want in the request body and I got the contact created in my org with all those fields filled with the data provided. While working by this method, you need to take care of some things like:- the date format should be like:- YYYY-MM-DD in case of date field so that it can be easily parsed, the boolean field should have a value as:- true/false in lowercase like I am having for Contact_Relationship__c field and also the field names are not case sensitive but you need to take care of the underscores ( _ ) and the ending __c in case of custom fields.

So, using this method, you can get the whole request body, perform your operations and return an appropriate response from the API without having a lot of method parameters.

That's all for this tutorial, in the next tutorial we'll explore the DELETE method in detail. The whole code of this tutorial is available in the post branch of my SFDC-Integration-Tutorial github repository which can be viewed by clicking here.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



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

Happy Trailblazing..!!

Monday, 4 November 2019

Salesforce Integration Tutorial Part 2 - Exploring GET Method

Hello Trailblazers,

This is the second tutorial in the Salesforce Integraton Tutorial Series. In the previous tutorial, we had an introduction about the various methods available while interacting with the REST APIs in Salesforce. You can have a look at the same by clicking here. In this tutorial, we're going to jump into code and will explore the GET method in detail. Throughout the whole series, we're going to work with the predefined Contact object and will be performing operations on this using the custom REST APIs.

To create a custom API, the first step is to create an apex class with a @RestResource annotation which is of the format:- @RestResource(urlMapping='your-custom-url'). In a single apex class which is annotated with @RestResource, we can create 5 methods each with a different annotations for the 5 request types i.e.:- GET, POST, PUT, DELETE and PATCH.

Each request type has it's own annotation available. For ex:- For GET method I am going to use the @HTTPGet annotation. You cannot create multiple methods with the same annotation. For ex:- If I try to create multiple methods in the same apex class with @HTTPGet annotation, then it's not allowed and I'll get an error as:- Only one method per type can be defined with: HttpGet.

Moving ahead, let's have a look at the below code:-


As you can see above, I have created an apex class named ContactResource with the urlMapping as /ContactAPI/*. This means that my custom API will be available at the endpoint:- /services/apexrest/ContactAPI/. I have created a single method named as getContactIdAndNames and this method is having the @HTTPGet annotation. This means that if I make a GET request to my API URL, this method will be called automatically.

Our getContactIdAndNames method will return a list of contact with each contact's salesforce id and the name of the contact in the response. The size of the list will depend on the URL parameter that we'll provide in the URL while making the request. For example:- If I want to limit the contacts queried upto 5 records, my URL will be:- /services/apexrest/ContactAPI/5.

RestContext is a predefined class in apex that consist of request and response context variables. With this, I mean that I can access the whole incoming request by using the request context variable of RestContext class. RestRequest is also a predefined apex class which can be used to create/accept an HTTP request. As, in this case, I am accepting the request from another source, I have initialized contactRequest (instance of RestRequest) with the RestContext.request instance variable.

Now, I have the request, I am getting the request URI by using the requestURI variable of RestRequest class and assigning it to a string named contactRequestURI. The requestURI consists of the whole part of URL after /apexrest/ . In our case, if the URL I am hitting is:- /services/apexrest/ContactAPI/5 then the contactRequestURI will receive /ContactAPI/5. My next task is to retrieve the 5 from the URL so that I can apply the limit to my SOQL query. For this, I am getting the substring from the contactRequestURI using contactRequestURI.substring(contactRequestURI.lastIndexOf('/') + 1) where I have specified the starting index as:- contactRequestURI.lastIndexOf('/') + 1.

In our example, the string:- /ContactAPI/5 is having length of 13. However, the lastIndexOf() method with a / in the parameter will return 11 i.e. the index of last / considering the indexes from 0-12 so, 11 + 1 will be 12 which is passed to the substring() method as the starting index and as we've not specified the ending index, it'll be taken automatically as the length of string which is 13. Therefore, we'll get 5 in the substring which is ultimately converted into the integer named contactLimit and passed in the SOQL query as:- List<Contact> contactList = [SELECT Id, Name FROM Contact LIMIT :contactLimit];

Finally, the list of contacts named contactList is returned. You can test this API in the workbench and you can fetch the contacts present in your org as given below:-

As you can see above, I am having the contact list in the response with Id and Name of each contact. in the output response.You can also see the raw response i.e. the actual response in the JSON format as given below:-


Now, the question arises:-

What if I want to pass more than one parameter in the URL ?

In this case, you can use the params variable of the RestRequest class which will return all the parameters passed in the URL in the form of Map<String, String>. For this, I have created a new class named ContactResource1 and specified a URL of /ContactAP1/ and a method name:- getContactIdNameAndLeadSource for that. Let's have a look at the below code:-


As you can see above, I am getting the request parameters using contactRequest.params i.e. the params variable of the RestRequest class. I am assigning it to a Map<String, String> which has a name:- contactRequestParams. I'll be using 2 URL parameters named:- limit and leadsource whose values will be passed in the query. My URL parameters are in the form of key value pairs after ? in the URL. In our example, the URL I'll be using is:- /services/apexrest/ContactAPI1?limit=2&leadsource=web as you can see here, at the end of URL, I have a ? and then the two URL parameters:- limit with a value 2 and leadsource with a value Web. I am getting the value of these URL parameters in the apex code by:- contactRequestParams.get('limit') and contactRequestParams.get('leadsource') respectively and assigning them to variables contactLimit and leadSource.

Finally, I have a query as:- List<Contact> contactList = [SELECT Id, Name, LeadSource FROM Contact WHERE LeadSource =:leadSource LIMIT :contactLimit]; In this query, I am getting a list of contacts where the LeadSource is the leadsource specified in the URL params and the LIMIT is the contactLimit obtained from the limit URL parameter. I have also added LeadSource to the query so that we can make sure that we're getting the filtered contacts in the response. At the end, we're returning the queried list of contacts in the response.

When you'll test it from workbench you'll have the output as given below:-

As you can see above, my both the URL parameters are working perfectly. I am getting only 2 contacts according to my limit and both have the LeadSource as Web.

That's all for this tutorial, in the next tutorial we'll explore the POST method in detail. The whole code of this tutorial is available in the get branch of my SFDC-Integration-Tutorial github repository which can be viewed by clicking here.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



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

Happy Trailblazing..!!

Sunday, 3 November 2019

Salesforce Integration Tutorial Part 1 - Introduction and Setting up Workbench

Hello Trailblazers,

Previously, we learned:- How to connect to Salesforce with Postman. If you open postman, you'll see there are a different types of requests that we can make to an endpoint as shown below:-


Out of all these request types, our custom API will support the 5 types of requests that are highlighted in red above and those are:-

  1. GET:- Used to query/retrieve records. We don't have any request body in this case. We send the information required to retrieve data in the URL parameters.
  2. POST:- Used to create new records. In this case, we send data to the server in the request body. This is more secure as compared to GET as we don't expose any data in the URL parameters. We send our data in the request body instead. We usually perform the insert operation on the data in this case.
  3. PUT:- Used to update the existing records or create new records. It is usually specified to perform the upsert operation in which if a record id is specified in the data we're sending, it'll update that record with the new data specified in the request body, otherwise, it'll create a new record.
  4. PATCH:- Used to update fields in the existing records. In this case, we usually perform the update operation on the data given. So, the data must have a record id for the operation to be successful.
  5. DELETE:- Used to delete a record using the record id. We mainly require only the unique record id in this case which will be used to delete the record. No other information is required.

While each of the request type has it's own significance, the most commonly used are GET and POST.

Before moving ahead, I'll recommend you to go through:- How to connect to Salesforce with Postman tutorial if you want to learn how authentication actually works. I have connected my Salesforce Org with Postman and shown an example of hitting a standard Salesforce API. Once you're aware of the connectivity stuff, you can easily test the rest APIs that we're going to create. As an alternative you can also use the workbench tool which is available at:- https://workbench.developerforce.com.

To use workbench, follow the below steps:-

1. Go to https://workbench.developerforce.com and you'll see the below screen:-

2. From the environment dropdown, choose your desired environment. For developer/production orgs:- choose production and for sandboxes, choose sandbox.

3. Choose the desired API version (I usually choose the latest one) and check the checkbox saying I agree to the terms of service.

4. Finally, click on the Login with Salesforce button and you'll see the below login screen:-


5. Enter your credentials, and click on Log In. If you're using it for the first time, you'll see the below screen requesting authorization.


6. Click Allow and you'll be redirected to the below screen:-

7. From the menu above, hover over utilities and click on REST Explorer. You'll see the below screen:-

8. This is our REST API explorer and to test it out I'll use the standard API and will query the accounts present in my org. In the textbox as shown in the image above, replace the text to:- /services/data/v47.0/query/?q=SELECT+Name,Type+FROM+Account and click on Execute button.

9. As you can see in the above image, I have used the standard Salesforce Query API to query name and type of all the accounts present in my org and the result is returned to me as a response. You can also click on Show Raw Response below the textbox to see the raw response. The raw response is the actual JSON response body which we see in postman or in other system when we hit this API. The raw response of our query is given below:-


In this tutorial, you learned about the basic request types and we connected workbench tool with our salesforce org. Now, we're all set to start working on custom REST APIs and we'll be using workbench to test those APIs. We'll be using workbench because in this case, we don't need to set the access token in the header while hitting salesforce APIs as workbench does that automatically for us.

Now, it's your time to explore the standard REST APIs available using workbench. Also, have a look at the REST API Developer Guide for more information on the standard REST APIs. In the next tutorial, we'll be creating a custom API and explore the GET request type in detail.

Tired of reading or just scrolled down, don't worry, you can watch the video too.



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