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
|
|
public WITH sharing class MyRestApiCtrl {
@AuraEnabled
public static void postServiceApi(){
//Contact con = [SELECT Id, FirstName, LastName, Email, Phone FROM Contact];
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users/');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('x-api-key', 'reqres-free-v1');
//req.setBody('{"name":"vjy1", "email":"vjy@vjy.com", "phone","333444"}');
Map<String, Object> bodyData = NEW Map<String, Object>();
bodyData.put('name', 'vjy1');
bodyData.put('email','vijay@vijay.com');
bodyData.put('phone','3333333333');
req.setBody(JSON.serialize(bodyData));
Http h = NEW Http();
HttpResponse res = h.send(req);
System.debug('StatusCode ' + res.getStatusCode());
IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
system.debug('resMap ' + resMap);
String name = (String)resMap.get('name');
String email = (String)resMap.get('email');
String phone = (String)resMap.get('phone');
External_User__c USER = NEW External_User__c();
USER.Name = name;
USER.Email__c = email;
INSERT USER;
}ELSE{
system.debug('Status Code ' + res.getStatusCode());
}}//Anonymous Window//POST CALL anonymous window IN salesforce: MyRestApiCtrl.postServiceApi();
//START GET Method
//public class wrapGetData {@AuraEnabled public string avatar;
@AuraEnabled public string email;
@AuraEnabled public string first_name;
@AuraEnabled public string last_name;
}@AuraEnabled
public static List<wrapGetData> putDataService(){
Http h = NEW Http();
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users/');
req.setMethod('GET');
req.setHeader('Content-Type','application/json');
req.setHeader('x-api-key', 'reqres-free-v1');
HttpResponse res = h.send(req);
system.debug(res.getStatus());
List<wrapGetData> wrapList = NEW List<wrapGetData>();
IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
system.debug('resMap__1 ' + resMap);
List<Object> objList = (List<Object>) resMap.GET('data');
system.debug('objList__1 ' + objList);
FOR(Object obj:objList){
Map<String, Object> objMap = (Map<String, Object>) obj;
system.debug('objMap ' + objMap);
String avatar = (String) objMap.get('avatar');
String email = (String) objMap.get('email');
String first_name = (String) objMap.get('first_name');
String last_name = (String) objMap.get('last_name');
wrapGetData wrap = NEW wrapGetData();
wrap.avatar = avatar;
wrap.email = email;
wrap.first_name = first_name;
wrap.last_name = last_name;
wrapList.add(wrap);
}}system.debug('wrapList ' + wrapList);
RETURN wrapList;}// Anonymous Window//GET CALL anonymous window IN salesforce: MyRestApiCtrl.putDataService();
//START PUT Method
////@AuraEnabled
public static void updatePutService(Id userId){
External_User__c USER = [SELECT Id, Name, Email__c FROM External_User__c WHERE Id =:userId];
Http h = NEW Http();
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users/');
req.setMethod('PUT');
req.setHeader('Content-Type','application/json');
req.setHeader('x-api-key', 'reqres-free-v1');
Map<String, Object> bodyData = NEW Map<String, Object>();
bodyData.put('name', 'Viy_11');
bodyData.put('email', 'vijay1@vijay.com');
req.setBody(JSON.serialize(bodyData));
HttpResponse res = h.send(req);
system.debug('statusCode ' + res.getStatusCode());
IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
system.debug('resMap_ ' + resMap);
string name = (String) resMap.get('name');
string email = (String) resMap.get('email');
USER.Name = name;
USER.Email__c = email;
UPDATE USER;
}system.debug('Updated Value ' + USER);
}//Anonymous window//GET CALL anonymous window IN salesforce: MyRestApiCtrl.updatePutService();
//START PATCH Method
public static void patchService(Id userId){
Http h = NEW Http();
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users/');
req.setMethod('PATCH');
req.setHeader('Content-Type','application/json');
req.setHeader('x-api-key', 'reqres-free-v1');
Map<String, Object> bodyData = NEW Map<String, Object>();
bodyData.put('name','Vijay KR');
bodyData.put('email','vijaykr@example.com');
req.setBody(JSON.serialize(bodyData));
HttpResponse res = h.send(req);
system.debug(res.getStatusCode());
List<External_User__c> userList = [SELECT Id, Name, Email__c FROM External_User__c WHERE Id =:userId];
IF(res.getStatusCode() == 201 || res.getStatusCode() == 200){
Map<String, Object> resMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
String name = (String) resMap.get('name');
String email = (String) resMap.get('email');
External_User__c u = NEW External_User__c();
IF(userList[0].Name == name){
u.Name = name;
u.Email__c = email;
u.id = userList[0].id;
UPDATE u;}ELSE{
u.Name = 'New User2';
u.Email__c = 'newuser@example.com';
INSERT u;}}}//Anonymous window//GET CALL anonymous window IN salesforce, pass the External_User__c Id: MyRestApiCtrl.patchService('a0RJ1000000jARpMAM');
//////START DELETE Method
public class wrapDeleteData{@AuraEnabled public string message;
@AuraEnabled public BOOLEAN isDeleted;@AuraEnabled public List<External_User__c> exUserList;
}public static wrapDeleteData deleteService(Id recordId){
wrapDeleteData wrap = NEW wrapDeleteData();
External_User__c USER;try{USER = [SELECT Id FROM External_User__c WHERE Id =:recordId];
}catch(exception e){
system.debug('Exception Error ' + e.getMessage());
wrap.isDeleted = FALSE;
wrap.message = 'External User Not Found';
wrap.exUserList = [SELECT Id, Name,Email__c FROM External_User__c LIMIT 10];
}Http h = NEW http();
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users/' + recordId);
req.setMethod('DELETE');
req.setHeader('Content-Type', 'jason/application');
req.setHeader('x-api-key', 'reqres-free-v1');
HttpResponse res = h.send(req);
System.debug('DELETE API STATUS: ' + res.getStatusCode());
system.debug('res ' + res);
DELETE USER;
wrap.isDeleted = TRUE;
wrap.message = 'Record Deleted Succesfully';
wrap.exUserList = [SELECT Id, Name,Email__c FROM External_User__c LIMIT 10];
system.debug('isDeleted ' + wrap.isDeleted);
system.debug('isDeleted ' + wrap.message);
system.debug('exUserList ' + wrap.exUserList);
RETURN wrap;}//Anonymous Window//DELETE CALL anonymous window IN salesforce, pass the External_User__c Id: MyRestApiCtrl.patchService('a0RJ1000000jARpMAM');
}
Further post that would you like to learn in Salesforce
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.
Related Topics | You May Also Like
|
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β |
