I am receiving this error: you have uncommitted work pending. please commit or rollback before calling out. What do I need to change in below code to resolve this? The error is on bold line in code below. Thank you!

Here's what I need to do in my code:1) when a lead is inserted, make a post request using the static resource 'EmedCalloutBody' as the body of the request. 2) If successful, that initial request returns a Request Id. 3) i can ONLY make that initial request once, or it can mess up the api endpoint queue- this is the part that is getting me stuck. 4) I need to take that request id and then use it to make a 2nd post request (then that will return json, which i will parse out, but have not done yet in the posted code). I need to keep on posting the 2nd request until I receive a response. I've seen some other posts but don't get how to apply them to my use-case scenario.

In the code below, I make the initial request and assign the returned requestId to a field, and make the update to the lead (last line of the class) on the Lead record as well as to a static string in the code. It's causing this error message you have uncommitted work pending. please commit or rollback before calling out.


trigger  ReferralCreateContact on Lead (after insert, after update) {

     List<string> leadIds = new List<string>();
    for (lead ref : trigger.new){
        if (ref.Epaces_Checked__c != true && (ref.Emed_Request_Id__c == null || ref.Emed_Request_Id__c == '')){
          lead newl = new lead();
          newl.Id = ref.id;


public class EMedCalloutsExtension {
    static string EmedrequestId;
     @future(callout = true)
       public static void  makePostCallout1(list<id> refIds) {
   List <Lead> refs =[Select Id, firstname, lastname, gender__c, patient_dob__c, patient_ssn__c, Epaces_Checked__c, Emed_Request_Id__c from Lead where Id in :refIds]; 
     List<lead> reftoupdate = new list<lead>();   
           for (lead ref : refs){
 string reqbody;
     StaticResource r =[Select Id,Body from StaticResource where Name='EMedCalloutBody' limit 1];
       HttpRequest req = new HttpRequest();
           req.setHeader('Content-Type', 'application/json');
                req.setTimeout(2 * 60 * 1000);
                    system.debug('ENDPOINT: ' + req.getendpoint());
                       system.debug('BODY: '+ req.getBody());
         Http http = new Http();
           HttpResponse response = http.send(req);
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
             string requestId = response.getbody().substringAfter('"request_id": ').substringBefore(',');
            EmedrequestId = requestId;
            if (ref.Emed_Request_Id__c == null || ref.Emed_Request_Id__c == ''){    
            ref.Emed_Request_Id__c = requestId;
                reftoupdate.add(ref); }

               if (ref.Emed_Request_Id__c != null){
                   EmedrequestId = ref.Emed_Request_Id__c;

              string reqbodyResp;   
              StaticResource r2 =[Select Id,Body from StaticResource where Name='EmedResponseBody' limit 1];
              reqbodyResp=reqbodyResp.replace('{{requestId}}', EmedrequestId);
                  HttpRequest req2 = new HttpRequest();
           req2.setHeader('Content-Type', 'application/json');
                req2.setTimeout(2 * 60 * 1000);
            system.debug('ENDPOINT2: ' + req2.getendpoint());
            system.debug('BODY2: '+ req2.getBody());
             Http http2 = new Http();
           HttpResponse response2 = http2.send(req2);
        if (response2.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response2.getStatusCode() + ' ' + response2.getStatus());
        } else {
           if (!reftoupdate.isempty()){  
               update reftoupdate; }
  • It is very difficult to follow the execution path and logical structure of your code because the formatting is so inconsistent. Please use a formatter like Prettier to clean up your code so that others can read it. – David Reed Sep 9 '20 at 15:20
  • 2
    This is an extremely common error. If you search SFSE, you will find many examples of how to handle it. – David Reed Sep 9 '20 at 15:20
  • Also, please try to bulkify the trigger params. You can convert the list to JSON and pass to a future method and there you can process bulkifed manner. – Ysr Shk Sep 9 '20 at 15:29
  • I don't think so. In that example there is only one callout being made. I'm not sure how that would apply to this scenario. I've also tried making 2 different trigger events: 1) after insert of the lead, make the intiial callout, and udpate the lead record with the paremeter for the 2nd callout, 2) after update, take that parameter and make the 2nd callout. However then I get a different error: Future method cannot be called from a future or batch – Michael M Sep 9 '20 at 16:46
  • Sounds like you've solved the DML error. Future method cannot be called is a different issue. Do a search, all of this has been covered in other questions many times. – identigral Sep 9 '20 at 18:15

Browse other questions tagged or ask your own question.