how to solve callout error? You have uncommitted work pending. Please commit or rollback before calling out

The issue occurs when you first perform DML and then callout in the same transaction

check this doc

You have uncommitted work pending. Please commit or rollback before calling out

You need to perform Callout in the future method so your callout and DML will be in the different transaction

This way you can resolve this issue

create a list and serialize it to pass to the future method. Because we can't pas list of sobject as a parameter in the future method

insert listofAccount;

string jsonString = JSON.serializePretty(listofAccount );

callout(jsonString);

In future method make callout

@future(callout = true)
public static void callout(string jsonString){
    //do callout here rest or soap
}

this way you can solve this issue.


So many wrong answers here... You definitely CAN do a callout and then DML in same transaction. You cannot do it THE OTHER WAY AROUND. Only Oles Malkov got it right.

Also switching to @future may not always help, as Asnyc Apex also may result in the same exception:

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