Callout from Trigger

By in
2441
Callout from Trigger

On certain occasions, you’ll need to make an API call to an external system to get or post some data to or from Salesforce. Think about what will happen if you make a callout and wait for the third-party system’s response after doing so in a Trigger. The user will have to wait for the response, which we want to avoid. Below, we’ll discuss API callouts from triggers and callouts from asynchronous apex processes to determine what your options are.

 

Salesforce Restriction

As mentioned above, we must avoid or lessen the user’s wait time after every DML. To do so, Salesforce has put a restriction on whether or not you can make an API call from the trigger. Salesforce wouldn’t allow you to make a callout from the Async execution context of the trigger. Hence you’d need to make the callout from an asynchronous apex process.

 

Bypassing the Restriction

Even though there’s the restriction of not allowing API callouts from triggers, there’s a workaround to make it happen. You can use Asynchronous Apex to make callouts. You’d be wondering how this would help. The answer lies in the question itself. An Asynchronous process is different from the execution thread of the trigger. Hence the user won’t have to wait for the response and the DML will happen quickly. Since it’s an asynchronous process, a background process will be invoked when the callout sends back a response to Salesforce. We can use the response to update the record that started the trigger operation.

 

global class WGAsyncHandler {

@future (callout=true)

Public static void doCallout(String a)

{

// API call

}

}

 

 

In a trigger when you need to make a callout, call a different method which will be asynchronous in nature and will have @future annotation.

 

Conclusion

As mentioned in the article, always make use of Future methods to make a callout. It’d also help in doing processing that would otherwise make you hit the CPU timeout exception.

 

To learn more about Apex triggers, check out some of my related blogs below!

 

Additional Resources

Cover Photo by abi ismail on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *