Salesforce Apex REST API | Basic + Hands On

Salesforce Apex REST API | Basic + Hands On

SALESFORCE APEX REST API

In the previous EPISODE of Integration series, we discussed the Basics of Integration before you started with Salesforce integration.

In this EPISODE, we are gonna discuss everything you need to know about salesforce apex REST API. Everything from scratch. Don't worry Kid, Integration is just a fancy word to define a bridge. Bridge ?? Yeah correct with integration will help you to connect two countries in our terminology its a bridge which allows you to connect two different types of application.  Hence to accept the data or to send the data to any external application system we use these API. In this EPISODE we will learn how to create REST API and how to use it to accept the data from the external system to salesforce.

WHAT IS APEX REST ?
So Apex REST is a way to expose the salesforce objects with the third party and perform operations with that. 
For example, If you have any E-commerce site let's say Shopify. Now you want all information about your products and all its information like product price and description from salesforce, in that case, we will develop these Apex REST API Classes. 
NOTE: This Apex REST API supports(accepts) data in XML and JSON format.
Relax it's just an Apex class with some fancy annotation and little different syntax.

Let's take look at the simple syntax of APEX REST API :
------------------------------------------------------------------------
@RestResource(urlMapping = '/salesforcekid/')
Global class myRestAPI{

}
------------------------------------------------------------------------
As you can see in the above syntax /salesforcekid/ is the URL which you will use from the external system to hit and send the data on.

Let me explain this in brief, these API what we will create gonna have one URL which is /salesforcekid/ in our case. So next time whenever web developer is asking for the API from you just provide this URL to him. With this URL he will send the data from the other system and with this URL only that data will enter in the salesforce. Gotcha ??

NOTE :
- The Apex class you are creating should be global so that it can be accessible fro external systems as well.
- This Apex class must be with annotation @RestResorce.
- When defining the URL in the REST Apex it should always start with / and ends with / as this is the pattern you need to follow and as you know in between whatever URL you want you can define that.
Now there are more annotation which you need to use based on the requirement, Let's have a look at 6 annotations that will help you to expose your REST API Apex class as a RESTful Service :

1. @RestResource(urlMapping='/yourURLNameHere/') :
This annotation is used at the beginning of your apex class which allows a third party system to hit this URL. 

2. @HttpDelete : 
When you want to delete the record from salesforce based on a request from the third party system. For Example: If the product is deleted from the Shopify website then delete that product from salesforce.
A method with this annotation doesn't require any particular body to be sent from the third party.

3. @HttpGet :
Whenever you want to get or retrieve the record from salesforce then we use this annotation above your method. For Example: Whenever you want to fetch the data of your products then you will use this annotation.
A method with this annotation doesn't require any particular body to be sent from the third party.

4. @HttpPatch :
This is an interesting annotation as this allows you to update an existing record in Salesforce or else if the record doesn't exist then it will create a new record inside salesforce. This is just like an upsert DML operation. For Example: If you updated some product information on your website then update the same information in salesforce if that record is already present or create a new record. 
A method with this annotation requires a particular body to be sent from the third party in JSON or XML format.

5. HttpPost :
This annotation use to create a record in salesforce from external system data. This is the most common annotation used. For Example: If a new product is uploaded or created on your website and you want to create those in salesforce as well to maintain the product data, In such scenarios, you will use this annotation in your REST Apex Class.
A method with this annotation requires a particular body to be sent from the third party in JSON or XML format.

6.  @HttpPut  :
This annotation is used to simply update the record in salesforce. For Example: When any product pricing updated on your Shopify website then update the same in salesforce.
A method with this annotation requires a particular body to be sent from the third party in JSON or XML format.

For Example :
------------------------------------------------------------------------
@RestResource(urlMapping='/salesforceKid/*')
 global with sharing class myRestAPI
{
  @HttpGet
  global static void getData(){}

  @HttpPost
  global static void postData(){}

  @HttpPut
  global static void putData(){}

  @HttpDelete
  global static void deleteData(){}
 }
------------------------------------------------------------------------

NOTE:
- Every @RestResorce class can have only one method with the same annotation. For Example, the class can only have one method with the above annotations.
- If you are calling @httpMethod from 3rd party then you need to append ?_httpMethod=PATCH at the end of the URL and set POST as the method.
- If two classes have the same URL in urlMapping then the class with the latest modified date will be considered.
- RestRequest and RestResponse object are available by default in your Apex methods through the static RestContext object.
- To get the params from the URL use RestContext.request.params, it will return the Map<String, String>
Now, this is about syntax to be used inside salesforce. Let's quickly have a look at the URL syntax of the external system to send the data to salesforce :

API URL FOR EXTERNAL SYSTEM :

SYNTAX:
------------------------------------------------------------------------
https://instance.salesforce.com/services/apexrest/customNamspace/YourURL
------------------------------------------------------------------------

https://instance.salesforce.com/ :
This is your salesforce org URL which you can easily find out when you logged in to your org.

services/apexrest/ :
This will tell you that the URL is exposed via APEX REST service

/customNamspace/ :
This is your org namespace if it is defined in a custom namespace. It's an option so if it's present or enabled in your system then only you need this in the URL.

YourURL :
This is the URL which we specified in our apex class. Just like in the above example we defined /salesforcekid/ as a URL.

HANDS ON :

Now before starting with this coolest part please log in to your salesforce org. In this hands-on session, we will send some data from an external system (I am going to to use workbench here). Then we will send some data from a workbench and hit this APEX REST API Url. Then we will perform operations in salesforce.

Let's begin........Kid

Before You started  :

Create a custom Product object :


Create One new custom field as Product Code :


Now create some sample records in your org before proceeding further.

Now create APEX Class Called 

myRestAPI.apxc
-----------------------------------------------------------
@RestResource(urlMapping='/salesforcekid/')
global class myRestAPI {
    @HttpGet
    global static Product__c getProducts(){
    //create a new instance for product object
    Product__c prod = new Product__c();
    //As params returns in Map<string, string> format and request the params
    Map<string, string> paramsMap = RestContext.request.params;
    //It will get the Id passed from external system
    string prodId = paramsMap.get('Id');
    //Query the product record
    prod = [Select Id, Name, Product_Code__c From Product__c Where Id =: prodId];
    //return the product with that id
    return prod;
    }
    
    @HttpDelete
    global static String deleteProducts(){
    //create a new instance for product object
    Product__c prod = new Product__c();
    //As params returns in Map<string, string> format and request the params
    Map<string, string> paramsMap = RestContext.request.params;
    //It will get the Id passed from external system
    string prodId = paramsMap.get('Id');
    //Query the product record
    prod = [Select Id, Name, Product_Code__c From Product__c Where Id =: prodId];
    //Delete the product from salesforce
    Delete prod;
    //return the String 
    return 'Product Deleted';
    }
    
    @HttpPost
    //Name and ProductCode will come from external system as a input
    global static Product__c createProducts( String Name, String ProductCode){
    //Create an instance of products
    Product__c prod = new Product__c();
    //Map the input params to name and productCode
    prod.Name = Name;
    prod.Product_Code__c = ProductCode;
    //insert the product
    insert prod;
    //Return this product to the third party system as a response
    return prod;  
    }
    
    @HttpPut
    //Name and ProductCode will come from external system as a input
    global static Product__c updateProducts( String Name, String ProductCode){
    //As params returns in Map<string, string> format and request the params
    Map<string, string> paramsMap = RestContext.request.params;
    //It will get the Id passed from external system
    string prodId = paramsMap.get('Id');
    //Create an instance of products
    Product__c prod = new Product__c();
    //Map the input params to Id, name and productCode 
    prod.Id = prodId;
    prod.Name = Name;
    prod.Product_Code__c = ProductCode;
    //insert the product
    update prod;
    //Return this product to the third party system as a response
    return prod;  
    }  
}
-----------------------------------------------------------

Above Apex class is self-explanatory code for each Annotation REST Method. 
Now its time to test this REST API and all the methods create, delete, update product record.

Now as I mentioned before, we are gonna use workbench as a platform as an external system.
      
STEP 1 :

Search on google for workbench or enter this URL: https://workbench.developerforce.com/restExplorer.php

Then you will be landed on its home screen :

CLICK ON : SignIn with Salesforce and login to your salesforce org.
-----------------------------------------------------------
-----------------------------------------------------------

STEP 2 :

Now from Utility tab select REST Explorer
-----------------------------------------------------------
-----------------------------------------------------------

STEP 3 :

Now enter our URL of REST API Class as follows :
-----------------------------------------------------------
-----------------------------------------------------------

Now, all set....we will check our every method one by one :

For GET Method :
As we know the Get method will give/retrieve the record information from the product object. Hence make sure sample records are created in your org.
Enter the Id of any product record created in your salesforce org by selecting get method in workbench and pass that salesforce record Id and execute like this :
-----------------------------------------------------------
-----------------------------------------------------------
As you can see as a response I received the Product Name and Product Code.
Coool right ?? 😊

Now next...

For DELETE Method :
For this also we need to pass Id of record to be deleted. So for this also we need to pass the Id in the same way. But this time in workbench we will select method as Delete
And I will pass the same Id of the record to be deleted. and hit execute and check what response we will get. 

-----------------------------------------------------------
-----------------------------------------------------------

As you can see we received the response as a string as expected and for verification, you can check the record in your salesforce org whether its deleted or not.

For POST Method :
As we know for POST further methods we need to follow a pattern of sending the data in JSON or XML format.
For this type please select method as POST in workbench and pass the record data as follows and let's check whether this will create a record in salesforce or not. 
Let's pass the JSON data like this and hit execute :
-----------------------------------------------------------
-----------------------------------------------------------

Wooohoo.....It's created the record in salesforce with these details...and returned the record details as expected.

For PUT Method :
Now next is Put for updating we need to follow the same pattern like POST but this time we need to pass the id in the URL also in the workbench and we are updating the product code here from "1234" to "P-00123" like this :
-----------------------------------------------------------
-----------------------------------------------------------

Wooooh.....Finally after executing you will update the old record with this new one.

Awesome Kid...Now next time if someone asks you to integrate the system with REST API don't panic because now you know how to do that with this easy methodology.

WOHOOO !! YOU HAVE JUST COMPLETED APEX REST API SALESFORCE EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all
Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 


SalesforceKid On Play Store

Salesforce Apex REST API | Basic + Hands On Salesforce Apex REST API | Basic + Hands On Reviewed by on Rating: 5

5 comments:

  1. Replies
    1. Thanks 😊

      ⚡ HAPPY LEARNING ⚡

      Delete
  2. Images are not available , can you please help ?

    ReplyDelete
    Replies
    1. Sorry for the inconvenience! I have fixed the images and now they are available.

      ⚡️HAPPY LEARNING⚡️

      Delete

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.