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:
- 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
TRIGGER ContactPracticeTrigger ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE) {
IF(TRIGGER.isAfter){
IF(TRIGGER.isUpdate){
List<Id> conIds = NEW List<Id>();
FOR(Contact con:TRIGGER.new){
Contact oldData = TRIGGER.oldMap.get(con.Id);
IF(con.Phone != oldData.Phone || con.Email != oldData.Email){
conIds.add(con.Id);
}}IF(!conIds.isEmpty()){
ContactPracticeBatch batch = NEW ContactPracticeBatch(NEW List<Id>(conIds));
DATABASE.executeBatch(batch, 5);
//ContactPracticeBatch.run(conIds);
}}}}
Step 2 Apex Controller: ContactPracticeBatch.apxc
public class ContactPracticeBatch implements DATABASE.Batchable<SObject>, DATABASE.AllowsCallouts {
public List<Id> contactIds;
public ContactPracticeBatch(List<Id> ids){
this.contactIds = ids;
}/*public static void run(List<Id> ids) {Database.executeBatch(new ContactPracticeBatch(new Set<Id>(ids)), 10);}*/public DATABASE.QueryLocator START(DATABASE.BatchableContext BC){
String query = 'Select Id, FirstName, LastName, Email, Phone, External_Customer_Id__c From Contact Where Id IN:contactIds';
RETURN DATABASE.getQueryLocator(query);
}public void EXECUTE(DATABASE.BatchableContext BC, List<Contact> scope){
List<Contact> conItem = NEW List<Contact>();
FOR(Contact con:scope){
string externalId = sendContactToExternalSystem(con);
con.External_Customer_Id__c = externalId;
conItem.add(con);
}IF(!conItem.isEmpty()){
UPDATE conItem;}}public void finish(DATABASE.BatchableContext BC){
system.debug('Batch Executed Successfully');
}//Rest Api Methodpublic string sendContactToExternalSystem(Contact con){
Http h = NEW Http();
HttpRequest req = NEW HttpRequest();
req.setEndpoint('https://reqres.in/api/users'); // Public test API
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('x-api-key', 'reqres_4d079b1969e2489f803812be427d6bc3vvvxxx');
//req.setBody('{"fname":con.FirstName, "lname":con.LastName, "email":con.Email, "phone":con.Phone}');
Map<String, Object> bodyData = NEW Map<String, Object>();
bodyData.put('fname',con.FirstName);
bodyData.put('lname',con.LastName);
bodyData.put('email',con.Email);
bodyData.put('phone',con.Phone);
req.setBody(JSON.serialize(bodyData));
HttpResponse res = h.send(req);
system.debug('StatusCode ' + res.getStatusCode());
IF(res.getStatusCode() == 200 || res.getStatusCode() == 201){
Map<String, Object> resData = (Map<String, Object>) json.deserializeUntyped(res.getBody());
system.debug('resData ' + resData);
string resId = (String) resData.get('id');
//con.External_Customer_Id__c = resId;
//UPDATE con;
RETURN resId;}RETURN NULL;
}}
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 |
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.
Related Topics | You May Also Like
|
👉 Get Free Course →
📌 Salesforce Administrators 📌 Salesforce Lightning Flow Builder 📌 Salesforce Record Trigger Flow Builder |
👉 Get Free Course → |
