+ 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.


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){

      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
      // ..
      // 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.

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();    
    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')) {
                accessToken += parser.getText();              
    system.debug('access token******* : ' + accessToken);
    req.setEndpoint( 'https://biswadevp-dev-ed.my.salesforce.com/services/data/v35.0/sobjects/Account');
    req.setHeader('Authorization', 'OAuth ' + accessToken);
    req.setHeader('Content-Type','application/json' );
    string Name = 'Biswajeet rest api Sree';   
    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.setHeader('Content-Type', 'application/json; charset=utf-8');
    req.setHeader('Authorization','Authorization: Bearer '+accessToken);   
    Http http1 = new Http();
    HTTPResponse res1 = http1.send(req);