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
Aditi Mohanty 5Aditi Mohanty 5 

How to insert record using rest api in place of "insert lstcont"


global class Batch_AddConToAcc implements Database.Batchable <sObject>,Database.Stateful,Database.AllowsCallouts {
     
     public List<String> nam=new List<String>();
     public Integer processedrecord=0;
    public String exp;
   String query = 'SELECT Id, Name FROM Account WHERE checkacc__c = True';
    global Database.QueryLocator start(Database.BatchableContext bc) {
         
        return Database.getQueryLocator(query);
    }

    global  void execute(Database.BatchableContext bc,List<Account> batch) {
       List<Account> acnt=new List<Account>();
        List<contact> lstCon = new List<Contact>();
        for (Account a : batch) {
           
            Contact c =  new Contact();
            c.LastName = a.Name;
        c.AccountId = a.Id;
            lstCon.add(c);
            a.checkacc__c = False;  
            acnt.add(a);
            processedrecord=processedrecord+1;
            nam.add(a.Name);
        }
        try{
         
       INSERT lstCon;
      
    }
        catch(Exception e){
            exp= e.getMessage();
        }
 update acnt;
        
        }
    
    global void finish(Database.BatchableContext bc) {
     

AsyncApexJob ajob = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
                          TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob WHERE Id =
                          :bc.getJobId()];
 EmailUtility.sendSimpleEmail(ajob.Status,processedrecord,nam,exp);      
        
        
      
        }     
       
    }
Danish HodaDanish Hoda
Hi Aditi, 
Can you help me with the business requirment, and what Rest API needs to do in this batch class?
 
AnudeepAnudeep (Salesforce Developers) 
There are several ways to do it. You can either make use of @RestResource in apex class or use tools like workbench to create record through REST explorer or even use CURL

The following example creates a new Account record, with the field values provided in newaccount.json.

Example for creating a new Account
curl https://yourInstance.salesforce.com/services/data/v51.0/sobjects/Account/ -H "Authorization: Bearer token -H "Content-Type: application/json" -d "@newaccount.json"
Example request body newaccount.json file for creating a new Account
{
  "Name" : "Express Logistics and Transport"
}

Example response body after successfully creating a new Account
{
  "id" : "001D000000IqhSLIAZ",
  "errors" : [ ],
  "success" : true
}

NOTE: The code provided is an example. You'll need to review and make modifications for your organization.

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you