function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vasavi VajinepalliVasavi Vajinepalli 

How to send the list of records in batches as a json string in http callout class

Hi All,

Am brand new to Salesforce and trying to send list of records in bathces(say 3000 records per batch). And my requirement is to send first 3000 records as a json string to third party API and get a response. If the response is success, then i need to send next 3000 records as json string again. Can anyone help me in sending the data as batches. If i get a response other success, i should not send the remaining data to API.

Thanks in advance.
Pankaj MehraPankaj Mehra
Hi Vasavi Vajinepalli,

You can use statefull batch where you can maintain a list of records in instance varaible once the list reaches a mark of 3000 record make a json string of 3000 records and hit the http callout and after the callout you have to clear the list (instance varaible) and from the next chunk the list is inserted again.

Please let me know if you need any more help on this.

Thanks


 
Vasavi VajinepalliVasavi Vajinepalli
Hi Pankaj Mehra,

Can you give me any sample examples for the above scenario? It would be great if you can give any working examples.
Pankaj MehraPankaj Mehra
Hi Vasavi Vajinepalli,

This is what i have in my mind : 

global class SummarizeAccountTotal implements 
    Database.Batchable<sObject>, Database.Stateful{
  
global String Query;

   global List<sObject> lstObject;
  
   global SummarizeAccountTotal(String q){Query=q;
     lstObject = new List<sObject>();
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator(Query);
   }
   
   global void execute(
                Database.BatchableContext BC, 
                List<sObject> scope){

      for(sObject s : scope){
    lstObject.add(s)
      }

      if(lstObject.size() =>  3000) {
      // Method that will convert the object list in Json
      String jsonString = makeJsonString(lstObject);

      // Make Callout
          Http http = new Http();
      HttpRequest request = new HttpRequest();
      // Other setting here
      // ..
      request.setBody(jsonString);
      http.send(request)
      // Clear list again
      lstObject = new List<sObject>();

      }

   }

global void finish(Database.BatchableContext BC){
   }
   
   
   // Method that will convert the object list in Json
   global String  makeJsonString(List<sObject> lstObject){
   }
}
Vasavi VajinepalliVasavi Vajinepalli
Thanks for the example Pankaj. But here, am not using Batch Apex. I heard that Batch context can be used only for Batch Apex. Am writing this callout code in an apex class. Is there any way to divide the data based on the total records and using index(means totalrecords/batchSize)?
Pankaj MehraPankaj Mehra
 Hi Vasavi Vajinepalli,

If you are doing incremental callouts then you need to use batch class as salesforce has limits in calling http requests in apex class. For the solution what I have understood the problem you can use recursive method in apex class as below :


public boolean makeIncrementalCallout(Id lastRecordId) {
List<sObject> lstObjects;
if(lastRecordId == null) {
// get first 3000 records
lstObjects = [Select Id from sObject order by CreatedDate ASC limit 3000 ];
} else {
lstObjects = [Select Id from sObject where Id > lastRecordId order by CreatedDate ASC limit 3000 ];
}
String jsonString = makeJson(lstObjects);

// Do the HTTP callout
.
.
// If callout is sucessfull, call the same method again\
makeIncrementalCallout(lastRecordId) // lastRecordId will be the Id of last record in the list 
}



 
Vasavi VajinepalliVasavi Vajinepalli
Hi Pankaj,

Can you please send me the complete code related to the above example, as am not able to understand the "lastRecordId" concept here. It would be helpful to me(beginner of salesforce :)) if you can send me an example with the above code.

thanks,
vasavi
RAM RRAM R
Hi Pankaj, 

is the above code working for insert multiple accounts through rest api cal? If you have any code please post here that will help me and i have written a code for create one record but i am not able to create multiple. find the below code.

Http http=new Http();
    HttpRequest req = new HttpRequest();    
    req.setendpoint('https://login.salesforce.com/services/oauth2/token');
    req.Setheader('username','password');
    req.setmethod('POST'); 
    req.setbody('grant_type=password&client_id=3MVG9ZL0ppGP5UrCJvSLOyskgcqZOX5ZlmXeoAb.Xgy5t5wZbaO.GcPzvwWnVodoLcv2PrHOm1jb6zY49MvZp&client_secret=7659060184564311663&username=biswajeet.pal@accenture.com.devp&password=biswajeet032');
    HttpResponse res;
    res = http.send(req);        
    String responseBody = res.getBody();
    system.debug('json response ******:' + res.getbody());
    system.debug('json response @@@@@@:' + http.send(req));
    String accessToken = '';    
    JSONParser Parser = JSON.createParser(responseBody);
        while(Parser.nextToken() != null){
            if((parser.getCurrentToken() == JSONToken.FIELD_NAME)&&(parser.getText()=='access_Token')) {
                parser.nextToken();
                accessToken += parser.getText();              
            }            
        }
    system.debug('access token******* : ' + accessToken);
   /*    
    req.setEndpoint( 'https://biswadevp-dev-ed.my.salesforce.com/services/data/v35.0/sobjects/Account');
    req.setMethod('POST');
    req.setHeader('Authorization', 'OAuth ' + accessToken);
    req.setHeader('Content-Type','application/json' );
    string Name = 'Biswajeet rest api Sree';   
    req.setBody(Name);
    Http http1 = new Http();    
    HttpResponse response = http1.send(req);
    system.debug('***Response****@@@@ : '+ http1.send(req));   */
    string accName = 'sreebiswajeet';
    string accPhone = '989898989';
    string accWebsite = 'google.com';
    string accbody = '{"name": "'+accName+'","phone": "'+accPhone+'","website": "'+accWebsite+'"}';
    String domainName='biswadevp-dev-ed.my.salesforce.com';
    String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
    req.setendpoint(endPointURL);
    req.setHeader('Content-Type', 'application/json; charset=utf-8');
    req.setBody(accbody);
    req.setmethod('POST');
    req.setHeader('Authorization','Authorization: Bearer '+accessToken);   
    Http http1 = new Http();
    HTTPResponse res1 = http1.send(req);
    System.debug('****************res.getStatusCode();'+res.getStatusCode());
    System.debug('****************res.getbody();'+res.getbody());