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

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

7 comments:

  1. Hi Rahul! Great Work! can you upload video of this tutorial.

    ReplyDelete
    Replies
    1. Hey buddy, so happy to see that you liked it. I am working on the same. Will start uploading videos after 2 more blogs in this series. Do share this in your network. Thanks :-)

      Delete
  2. Hi Rahul,
    Can we test this API in POSTMAN instead of workbench?

    ReplyDelete
  3. Hi Rahul,
    Can we test this API in POSTMAN instead of workbench?

    ReplyDelete
  4. Thanks Rahul, you explain all concept in details and with code part which is great andno need to refer elsewhere as it's more than enough

    ReplyDelete
    Replies
    1. Happy to know that you liked it :-) Do share it among others too..!!

      Delete