Apex Trigger to Sends Contact data to external system using POST API, External system returns External Customer ID, Salesforce updates Contact with External ID Using Batch Class in Salesforce

95 views

Apex Trigger to Sends Contact data to external system using POST API, External system returns External Customer ID, Salesforce updates Contact with External ID Using Batch Class in Salesforce

REAL-TIME BUSINESS SCENARIO (POST + BATCH)

📌 Scenario:

👉 Download Free Ebook →

👉 Get Complementary →

right side banner -- www.w3webmart.com
  • Salesforce has Contacts that are not yet synced with an External CRM
  • A Batch Apex job:
    • Sends Contact data to external system using POST API
    • External system returns External Customer ID
    • Salesforce updates Contact with External ID
  • Whenever a Contact is updated → Salesforce syncs changes back to external system (POST)

 

Create Custom Field on Contact

Field Label API Name Type
External Customer ID External_Customer_Id__c Text(50)

Batch Apex – POST Callout Controller

  • Queries unsynced Contacts
  • Sends POST API
  • Updates Contact with API response

 

Step 1 Account Trigger (After Update): ContactPracticeTrigger.apxt

  1.  
  2.  TRIGGER ContactPracticeTrigger ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE) {
  3.  
  4.     IF(TRIGGER.isAfter){
  5.  
  6.         IF(TRIGGER.isUpdate){
  7.  
  8.             List<Id> conIds = NEW List<Id>();
  9.  
  10.             FOR(Contact con:TRIGGER.new){
  11.  
  12.                 Contact oldData =  TRIGGER.oldMap.get(con.Id);
  13.  
  14.                 IF(con.Phone != oldData.Phone || con.Email != oldData.Email){
  15.                     conIds.add(con.Id);
  16.                 }
  17.  
  18.             }
  19.  
  20.             IF(!conIds.isEmpty()){
  21.                 ContactPracticeBatch batch = NEW ContactPracticeBatch(NEW List<Id>(conIds));
  22.                 DATABASE.executeBatch(batch, 5);
  23.  
  24.                 //ContactPracticeBatch.run(conIds);
  25.  
  26.             }
  27.  
  28.         }
  29.  
  30.     }
  31.  
  32. }

 

Step 2 Apex Controller: ContactPracticeBatch.apxc

  1.  
  2.      public class ContactPracticeBatch implements DATABASE.Batchable<SObject>, DATABASE.AllowsCallouts {
  3.  
  4.     public List<Id> contactIds;
  5.  
  6.     public ContactPracticeBatch(List<Id> ids){
  7.          this.contactIds = ids;
  8.     }
  9.   /*  
  10.     public static void run(List<Id> ids) {
  11.         Database.executeBatch(new ContactPracticeBatch(new Set<Id>(ids)), 10);
  12.     }
  13.  */
  14.  
  15.     public DATABASE.QueryLocator START(DATABASE.BatchableContext BC){
  16.         String query = 'Select Id, FirstName, LastName, Email, Phone, External_Customer_Id__c From Contact Where Id IN:contactIds';
  17.         RETURN  DATABASE.getQueryLocator(query);     
  18.     }
  19.  
  20.     public void EXECUTE(DATABASE.BatchableContext BC, List<Contact> scope){       
  21.         List<Contact> conItem = NEW List<Contact>();
  22.  
  23.         FOR(Contact con:scope){
  24.             string externalId = sendContactToExternalSystem(con);
  25.             con.External_Customer_Id__c = externalId;            
  26.             conItem.add(con);
  27.         }
  28.         IF(!conItem.isEmpty()){
  29.             UPDATE conItem;
  30.         }
  31.  
  32.     }
  33.  
  34.     public void finish(DATABASE.BatchableContext BC){
  35.        system.debug('Batch Executed Successfully');   
  36.     }
  37.  
  38.  
  39.  
  40.     //Rest Api Method
  41.     public string sendContactToExternalSystem(Contact con){
  42.  
  43.         Http h = NEW Http();
  44.           HttpRequest req = NEW HttpRequest();
  45.           req.setEndpoint('https://reqres.in/api/users'); // Public test API
  46.           req.setMethod('POST');
  47.           req.setHeader('Content-Type', 'application/json');
  48.           req.setHeader('x-api-key', 'reqres_4d079b1969e2489f803812be427d6bc3vvvxxx');        
  49.           //req.setBody('{"fname":con.FirstName, "lname":con.LastName, "email":con.Email, "phone":con.Phone}');
  50.  
  51.           Map<String, Object> bodyData = NEW Map<String, Object>();
  52.           bodyData.put('fname',con.FirstName);
  53.           bodyData.put('lname',con.LastName);
  54.           bodyData.put('email',con.Email);
  55.           bodyData.put('phone',con.Phone);
  56.           req.setBody(JSON.serialize(bodyData));
  57.  
  58.          HttpResponse res = h.send(req);
  59.         system.debug('StatusCode ' + res.getStatusCode());
  60.  
  61.         IF(res.getStatusCode() == 200 || res.getStatusCode() == 201){
  62.  
  63.             Map<String, Object> resData = (Map<String, Object>) json.deserializeUntyped(res.getBody());
  64.             system.debug('resData ' + resData);
  65.  
  66.             string resId = (String) resData.get('id');
  67.  
  68.             //con.External_Customer_Id__c = resId;
  69.             //UPDATE con;
  70.             RETURN resId;
  71.  
  72.         }
  73.  
  74.         RETURN NULL;
  75.  
  76.     }
  77.  
  78.  
  79. }

 

Further post that would you like to learn in Salesforce


🎁 Up to 99% Off Courses (Coupon)
💥 Use Promo Code: STANDARDOFFER💥
🚀 Get Free Salesforce Course Access: www.thevijaykumar.w3web.net

 

FAQ (Frequently Asked Questions)

How to send data from Salesforce to external system using rest API?

Use OAuth or another supported authentication method to obtain an access token. Make HTTP requests (GET, POST, PUT, DELETE) to Salesforce REST API endpoints, passing the access token in the header. Parse the JSON or XML responses to interact with Salesforce data (e.g., create, read, update, or delete records).

How to send data in POST API?

When you tell the API that you want to send information, you send a POST request to the server. After it processes your request, the server gets your information and processes it as intended. For a more technical definition of POST requests, click here.

What should API responses sent to external systems contain?

An API response consists of the response body, headers, cookies, and the HTTP status code.

👉 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