A complete External REST API integration using POST + GET + PUT + PATCH, and DELETE in Salesforce | Apex Class for External REST Integration in Salesforce

233 views

Hey guys, today in this post we are going to learn about A complete External REST API integration using POST + GET + PUT + PATCH, and DELETE in Salesforce | Apex Class for External REST Integration in Salesforce.

Let’s design a complete external REST API integration in Salesforce using @HttpGet and @HttpPost methods β€” where Salesforce acts as a client, consuming data from or sending data to an external system (for example, an external web service).

We’ll cover both use cases step-by-step:

  • @RestResource (urlMapping=’/myApexRestDemo/’):- Used at the top of the class which tell the URL to be hit from the 3rd party.
  • @HttpGet β†’ Fetch data from external API
  • @HttpPost β†’ Send data to external API (insert Contact record details)
  • @httpPatch:- It is used to update existing record in salesforce if record exists otherwise to create a new record.
  • @httpPost:- It is used to Create a record in salesforce
  • @httpPut:- It is to update the existing record in salesforce.

 

βœ… Step 1: Create the Apex Class for External REST Integration


  1.   public WITH sharing class MyRestApiCtrl {
  2.  
  3.  
  4.     @AuraEnabled
  5.     public static void postServiceApi(){ 
  6.  
  7.         //Contact con = [SELECT Id, FirstName, LastName, Email, Phone FROM Contact];
  8.  
  9.  
  10.         HttpRequest req = NEW HttpRequest();
  11.         req.setEndpoint('https://reqres.in/api/users/');
  12.         req.setMethod('POST');
  13.         req.setHeader('Content-Type', 'application/json');
  14.         req.setHeader('x-api-key', 'reqres-free-v1');
  15.         //req.setBody('{"name":"vjy1", "email":"vjy@vjy.com", "phone","333444"}');
  16.  
  17.         Map<String, Object> bodyData = NEW Map<String, Object>();
  18.         bodyData.put('name', 'vjy1');
  19.         bodyData.put('email','vijay@vijay.com');
  20.         bodyData.put('phone','3333333333');
  21.         req.setBody(JSON.serialize(bodyData));
  22.  
  23.  
  24.         Http h = NEW Http();
  25.         HttpResponse res = h.send(req);  
  26.  
  27.         System.debug('StatusCode ' + res.getStatusCode());
  28.  
  29.         IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
  30.  
  31.             Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
  32.  
  33.             system.debug('resMap ' + resMap);
  34.  
  35.             String name = (String)resMap.get('name');  
  36.             String email = (String)resMap.get('email');
  37.             String phone = (String)resMap.get('phone');
  38.  
  39.             External_User__c USER = NEW External_User__c();
  40.             USER.Name = name;
  41.             USER.Email__c = email;            
  42.  
  43.             INSERT USER;
  44.         }ELSE{
  45.             system.debug('Status Code ' + res.getStatusCode());
  46.         }
  47.  
  48.     } 
  49.  
  50.  
  51.    //Anonymous Window 
  52.    //POST CALL anonymous window IN salesforce: MyRestApiCtrl.postServiceApi();
  53.  
  54.  
  55.  
  56.  
  57.  
  58.     //START GET Method
  59.     //
  60.     public class wrapGetData {
  61.         @AuraEnabled public string avatar;
  62.         @AuraEnabled public string email;
  63.         @AuraEnabled public string first_name;
  64.         @AuraEnabled public string last_name;
  65.     }
  66.  
  67.     @AuraEnabled
  68.  
  69.     public static List<wrapGetData> putDataService(){
  70.  
  71.          Http h = NEW Http();
  72.          HttpRequest req = NEW HttpRequest();
  73.  
  74.          req.setEndpoint('https://reqres.in/api/users/');
  75.          req.setMethod('GET');
  76.          req.setHeader('Content-Type','application/json');
  77.          req.setHeader('x-api-key', 'reqres-free-v1');
  78.  
  79.          HttpResponse res = h.send(req);
  80.  
  81.          system.debug(res.getStatus());
  82.         List<wrapGetData> wrapList = NEW List<wrapGetData>();
  83.  
  84.         IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
  85.  
  86.             Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
  87.  
  88.             system.debug('resMap__1 ' + resMap);
  89.  
  90.             List<Object> objList = (List<Object>) resMap.GET('data'); 
  91.  
  92.             system.debug('objList__1 ' + objList);
  93.  
  94.  
  95.  
  96.             FOR(Object obj:objList){
  97.  
  98.                 Map<String, Object> objMap = (Map<String, Object>) obj;
  99.  
  100.                 system.debug('objMap ' + objMap);
  101.  
  102.                 String avatar = (String) objMap.get('avatar');
  103.                 String email = (String) objMap.get('email');
  104.                 String first_name = (String) objMap.get('first_name');
  105.                 String last_name = (String) objMap.get('last_name');
  106.  
  107.                 wrapGetData wrap = NEW wrapGetData();
  108.                 wrap.avatar = avatar;
  109.                 wrap.email = email;
  110.                 wrap.first_name = first_name;
  111.                 wrap.last_name = last_name;
  112.                 wrapList.add(wrap);
  113.             }
  114.  
  115.  
  116.  
  117.         }
  118.  
  119.         system.debug('wrapList ' + wrapList);
  120.         RETURN wrapList;
  121.  
  122.  
  123.     }
  124.  
  125.  
  126.     // Anonymous Window
  127.      //GET CALL anonymous window IN salesforce: MyRestApiCtrl.putDataService();
  128.  
  129.  
  130.  
  131.  
  132.  
  133.         //START PUT Method
  134.         //
  135.         //
  136.         @AuraEnabled        
  137.         public static void updatePutService(Id userId){
  138.  
  139.             External_User__c USER = [SELECT Id, Name, Email__c FROM External_User__c WHERE Id =:userId];
  140.  
  141.            Http h = NEW Http();
  142.            HttpRequest req = NEW HttpRequest();
  143.            req.setEndpoint('https://reqres.in/api/users/');
  144.            req.setMethod('PUT');
  145.            req.setHeader('Content-Type','application/json'); 
  146.            req.setHeader('x-api-key', 'reqres-free-v1');
  147.  
  148.            Map<String, Object> bodyData = NEW Map<String, Object>();
  149.  
  150.            bodyData.put('name', 'Viy_11');
  151.            bodyData.put('email', 'vijay1@vijay.com');           
  152.  
  153.            req.setBody(JSON.serialize(bodyData)); 
  154.  
  155.            HttpResponse res = h.send(req);
  156.  
  157.            system.debug('statusCode ' + res.getStatusCode());
  158.  
  159.             IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
  160.  
  161.                 Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
  162.  
  163.                 system.debug('resMap_ ' + resMap);
  164.  
  165.                 string name = (String) resMap.get('name');
  166.                 string email = (String) resMap.get('email');                
  167.  
  168.  
  169.  
  170.                 USER.Name = name;
  171.                 USER.Email__c = email;
  172.  
  173.                 UPDATE USER;
  174.  
  175.             }
  176.  
  177.             system.debug('Updated Value ' + USER);
  178.  
  179.  
  180.         }
  181.  
  182.     //Anonymous window
  183.     //GET CALL anonymous window IN salesforce: MyRestApiCtrl.updatePutService();
  184.  
  185.  
  186.     //START PATCH Method
  187.  
  188.     public static void patchService(Id userId){
  189.  
  190.         Http h = NEW Http();
  191.         HttpRequest req = NEW HttpRequest();
  192.  
  193.         req.setEndpoint('https://reqres.in/api/users/');
  194.         req.setMethod('PATCH');
  195.         req.setHeader('Content-Type','application/json');
  196.         req.setHeader('x-api-key', 'reqres-free-v1');
  197.  
  198.         Map<String, Object> bodyData = NEW Map<String, Object>();
  199.         bodyData.put('name','Vijay KR');
  200.         bodyData.put('email','vijaykr@example.com');
  201.  
  202.         req.setBody(JSON.serialize(bodyData));
  203.  
  204.         HttpResponse res = h.send(req);
  205.  
  206.         system.debug(res.getStatusCode());
  207.  
  208.         List<External_User__c> userList = [SELECT Id, Name, Email__c FROM External_User__c WHERE Id =:userId];
  209.  
  210.         IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
  211.  
  212.             Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
  213.  
  214.             String name = (String) resMap.get('name');
  215.             String email = (String) resMap.get('email');
  216.  
  217.             External_User__c u = NEW External_User__c();
  218.  
  219.             IF(userList[0].Name == name){
  220.                 u.Name = name;
  221.                 u.Email__c = email; 
  222.                 u.id = userList[0].id;
  223.                 UPDATE u;                               
  224.             }
  225.             ELSE{                                
  226.                 u.Name = 'New User2';
  227.                 u.Email__c = 'newuser@example.com';                
  228.                 INSERT u;
  229.             }
  230.  
  231.  
  232.         }        
  233.  
  234.     }
  235.  
  236.     //Anonymous window
  237.     //GET CALL anonymous window IN salesforce, pass the External_User__c Id: MyRestApiCtrl.patchService('a0RJ1000000jARpMAM');
  238.     //
  239.  
  240.  
  241.  
  242.    ////START DELETE Method
  243.  
  244.     public class wrapDeleteData{
  245.         @AuraEnabled public string message;       
  246.         @AuraEnabled public BOOLEAN isDeleted;
  247.         @AuraEnabled public List<External_User__c> exUserList;
  248.     }
  249.  
  250.  
  251.     public static wrapDeleteData deleteService(Id recordId){
  252.  
  253.          wrapDeleteData wrap = NEW wrapDeleteData();
  254.  
  255.         External_User__c USER;
  256.  
  257.         try{            
  258.  
  259.            USER = [SELECT Id FROM External_User__c WHERE Id =:recordId]; 
  260.  
  261.         }catch(exception e){
  262.             system.debug('Exception Error ' + e.getMessage());
  263.             wrap.isDeleted = FALSE; 
  264.             wrap.message = 'External User Not Found';
  265.             wrap.exUserList = [SELECT Id, Name,Email__c FROM External_User__c LIMIT 10];
  266.         }
  267.  
  268.  
  269.         Http h = NEW http();
  270.         HttpRequest req = NEW HttpRequest();
  271.         req.setEndpoint('https://reqres.in/api/users/' + recordId);
  272.         req.setMethod('DELETE');
  273.         req.setHeader('Content-Type', 'jason/application');
  274.         req.setHeader('x-api-key', 'reqres-free-v1');
  275.  
  276.         HttpResponse res = h.send(req);
  277.  
  278.          System.debug('DELETE API STATUS: ' + res.getStatusCode());
  279.  
  280.         system.debug('res ' + res);
  281.  
  282.         DELETE USER;
  283.  
  284.          wrap.isDeleted = TRUE; 
  285.          wrap.message = 'Record Deleted Succesfully';
  286.          wrap.exUserList = [SELECT Id, Name,Email__c FROM External_User__c LIMIT 10];
  287.  
  288.         system.debug('isDeleted ' + wrap.isDeleted);
  289.         system.debug('isDeleted ' + wrap.message);        
  290.         system.debug('exUserList ' + wrap.exUserList);
  291.  
  292.          RETURN wrap;
  293.  
  294.     }
  295.  
  296.     //Anonymous Window
  297.     //DELETE CALL anonymous window IN salesforce, pass the External_User__c Id: MyRestApiCtrl.patchService('a0RJ1000000jARpMAM');
  298.  
  299.  
  300.  
  301. }

 

Further post that would you like to learn in Salesforce

 

FAQ (Frequently Asked Questions)

What is an apex REST class?

You can expose your Apex class and methods so that external applications can access your code and your application through the REST architecture. This is done by defining your Apex class with the @RestResource annotation to expose it as a REST resource.

How can you expose an apex class as a REST webservice in Salesforce?

Making your Apex class available as a REST web service is straightforward. Define your class as global, and define methods as global static. Add annotations to the class and methods. For example, this sample Apex REST class uses one method.

What are the REST methods in Apex?

Apex REST supports two formats for representations of resources: JSON and XML. JSON representations are passed by default in the body of a request or response, and the format is indicated by the Content-Type property in the HTTP header.

πŸ‘‰ Get Complementary β†’

right side banner -- www.w3webmart.com
 
  
πŸ‘‰ Get Free Course β†’

πŸ“Œ Salesforce Administrators

πŸ“Œ Salesforce Lightning Flow Builder

πŸ“Œ Salesforce Record Trigger Flow Builder

πŸ‘‰ Get Free Course β†’

πŸ“Œ Aura Lightning Framework

πŸ“Œ Lightning Web Component (LWC)

πŸ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net