I'm trying to call a method which do an api call. But I'm getting an error because this method get call through the process ran by batch. So even if I directly call the API calling method it gives me an error 'Callout from triggers are currently not supported'. And when I call future method then it says future method cannot be called from batch. I have already implemented the Database.AllowsCallout interface in the batch class. Please help in this.Thank you.
2 Answers
Salesforce does not allow callouts in triggers or future methods from the batch class. I think your current code requires a little restructuring where you can make the callouts directly from the batch by isolating the logic that is being called in the trigger and calling it from the batch instead.
The other way to do that would add identification (like a field or picklist) to the record using the batch and using another batch just to make the callouts.
So, a good practice is to delegate callouts to queueable Apex. This allows the Queueable class to be invoked from either
- Trigger
- Batchable execute()
If you add an intermediate Async_Request__c
object that contains the callable parameters, you can build interesting async patterns that provide retry on error and logging of every callout. One example of this can be found in Advanced Apex, 4th Edition, chapter on Asynchronous Processing
You could also delegate callouts via Platform Events which execute asynchronously. The Platform Event subscriber would accept the callout params and then do the callout