How to Perform HTTP Callout from Apex Trigger?

Spread the love

Question

I have a trigger on a custom object that invokes an Apex class to make an HTTP GET request to an external web service. However, I encounter the following error:

“Callout from triggers are currently not supported.”

I understand that I can use an @future method to perform an asynchronous callout, but @future methods must return void, meaning they cannot return results. In my use case, I need to send data to the external service and receive an acknowledgment response.

Given the limitations of @future methods, what are the best approaches to making an HTTP callout from an Apex trigger while ensuring I can handle the response properly?

Answer

Salesforce does not support making HTTP callouts directly from a trigger because triggers execute synchronously, and callouts require an asynchronous context. However, there are several ways to work around this limitation.

1. Using Future Methods (Basic Approach)

Future methods (@future) are a common approach to handling callouts asynchronously. However, they cannot return values, which means you won’t get an immediate response in your trigger.

Here’s how you can implement a future method for a callout:

public class CalloutService {
    @future(callout=true)
    public static void makeCallout(String requestUrl) {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestUrl);
        request.setMethod('GET');

        HttpResponse response = http.send(request);
        System.debug('Response: ' + response.getBody());
    }
}

Then, in your trigger, invoke this method asynchronously:

trigger CustomObjectTrigger on CustomObject__c (after insert) {
    for (CustomObject__c record : Trigger.new) {
        CalloutService.makeCallout('https://api.example.com/data');
    }
}

However, this method does not allow you to capture the response directly in your trigger.

2. Using Queueable Apex (Recommended Approach Over Future Methods)

Queueable Apex is a more flexible alternative to future methods because it allows for callout support and chaining jobs if necessary.

public class CalloutQueueable implements Queueable, Database.AllowsCallouts {
    private String requestUrl;

    public CalloutQueueable(String requestUrl) {
        this.requestUrl = requestUrl;
    }

    public void execute(QueueableContext context) {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestUrl);
        request.setMethod('GET');

        HttpResponse response = http.send(request);
        System.debug('Response: ' + response.getBody());
    }
}

Invoke the queueable job from your trigger:

trigger CustomObjectTrigger on CustomObject__c (after insert) {
    for (CustomObject__c record : Trigger.new) {
        System.enqueueJob(new CalloutQueueable('https://api.example.com/data'));
    }
}

Queueable Apex provides better control and debugging than future methods, but it still relies on asynchronous execution limits.

3. Using Platform Events and Record Tagging (Scalable and Reliable Approach)

A better, more scalable approach is to use Platform Events and record tagging. Instead of making the callout directly from the trigger, you mark the record as needing processing and publish a Platform Event. A separate Apex event subscriber then picks up the event and makes the callout.

Step 1: Define a Platform Event

Create a new Platform Event, e.g., CalloutEvent__e, with the following fields:

  • RecordId__c (Text) – Stores the ID of the record that triggered the event.
  • RequestUrl__c (Text) – Stores the endpoint for the callout.

Step 2: Publish the Event from the Trigger

trigger CustomObjectTrigger on CustomObject__c (after insert) {
    for (CustomObject__c record : Trigger.new) {
        CalloutEvent__e event = new CalloutEvent__e(
            RecordId__c = record.Id,
            RequestUrl__c = 'https://api.example.com/data'
        );
        EventBus.publish(event);
    }
}

Step 3: Create a Platform Event Listener to Make the Callout

public class CalloutEventListener {
    @InvocableMethod
    public static void handleEvents(List<CalloutEvent__e> events) {
        for (CalloutEvent__e event : events) {
            System.enqueueJob(new CalloutQueueable(event.RequestUrl__c));
        }
    }
}

This method ensures that:

  1. The trigger executes quickly without callout limitations.
  2. The callout occurs asynchronously using Queueable Apex.
  3. If an event is lost, record tagging can be used to reprocess records.

Which Approach Should You Use?

  • Use Future Methods only if you don’t need the response and your use case is simple.
  • Use Queueable Apex if you need more control, logging, or the ability to chain jobs.
  • Use Platform Events and Record Tagging for high-volume transactions where reliability, scalability, and guaranteed processing are important.

For a robust implementation that ensures retries and avoids asynchronous limits, Platform Events with Queueable Apex is the best approach.

Kick Start Your Journey with Real-Time Project-Based Salesforce Learning

Our Salesforce Course is designed to provide a comprehensive understanding of the Salesforce platform, equipping you with the key skills needed to thrive in the CRM industry. The curriculum covers essential modules like Salesforce Admin, Developer, and AI, seamlessly integrating theoretical concepts with hands-on training. Through real-world projects and practical exercises, you’ll gain the expertise to tackle complex business challenges using Salesforce solutions. Our experienced instructors ensure you develop both technical proficiency and industry insights to excel in the Salesforce ecosystem.

In addition to technical skills, our Salesforce training in Hyderabad offers expert mentorship, certification guidance, and interview preparation to boost your career prospects. You’ll benefit from in-depth study materials, live project experience, and dedicated support throughout your learning journey. By the end of the course, you’ll be well-equipped for certification exams and possess the problem-solving abilities that employers highly value. Take the first step toward a successful Salesforce career with us— Enroll for a Free Demo today!

Open Chat
1
Dear Sir/Madam
How can I help you?