+ Start a Discussion
Diwakar G 7Diwakar G 7 

Post Request in Trigger in Batch Update

Hi,

I have one button which will do batch update and a trigger is written on the same object which checks the present and previous field value. If it is different then I need to make post api call.
Below are codes:

Apex Trigger:
trigger StatusChange on User_Story__c (after update) {
    
    List<User_Story__c> ulist = trigger.new;
    
    for(User_Story__c u: ulist){

    User_Story__c updacc=[select id,name,userStory_reason__c from User_Story__c where id = :u.id];

    if(Trigger.oldmap.get(updacc.id).userStory_reason__c != Trigger.newmap.get(updacc.id).userStory_reason__c){
        
        postrequest.apicall();

}

 }

}

Apex Class:
global class postrequest{

    @future(callout=true)
    public static void apicall(){
            HttpRequest req = new HttpRequest();
        	String endpoint = 'https://diwakarg029.pythonanywhere.com/leep';
        	String jsonData = 'ABC';
        	req.setbody(jsonData);
        	req.setEndpoint(endpoint);
                req.setHeader('Accept', 'application/json');
      		req.setMethod('POST');
      		Http http = new Http();
       		http.send(req);
    }


}
But, I am getting the below error. Please help me.
caused by: System.AsyncException: Future method cannot be called from a future or batch method:
Khan AnasKhan Anas (Salesforce Developers) 
Hi Diwakar,

Greetings to you!

Salesforce doesn't allow a future method to be called from another future method or a batch job. Before calling your future method, you should check if a future or batch job is already running. This would be a best practice for any code you ever write that calls a future method.
 
if(System.IsBatch() == false && System.isFuture() == false){ 
    // make your future call here 
}

Update the trigger logic to leverage the System.isFuture() and System.isBatch() calls so that the future method invocation is not made if the current execution context is future or batch. Record created through such cases should be handled separately using a scheduled batch job or something similar.

Or replace the future method with Queueable Apex.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm

https://developer.salesforce.com/blogs/developer-relations/2015/05/queueable-apex-future.html

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Diwakar G 7Diwakar G 7
Hi Khan,

In service function, I am not updating anything releated to User_Story__c object. No logic is written. Just it will written 'Hello from Flask!' response.

Thanks and Regards,
Diwakar G