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 

I have to insert records using Rest API in place of DML expression "insert lstCnt".How to do that?

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);      
        
        
      
        }     
       
    }

 
Vishwajeet kumarVishwajeet kumar
Hello,
REST API can be used for Inserting data into salesforce from external sytems. Apex Rest Service (https://trailhead.salesforce.com/en/content/learn/v/modules/apex_integration_services/apex_integration_webservices) can be created which can be called using REST API to do similar operation as done by code.

Thanks
Aditi Mohanty 5Aditi Mohanty 5
Hello, thanks for the reply.
But the solution you have provided, I am not finding it very much helpful. I need for batch apex, but it is for apex, which is confusing me. Since, I am new in this I need a proper solution.
Vishwajeet kumarVishwajeet kumar
Hello,
My previous reply was based on assumption that their is need to do same process as batch class using REST Api.
If requirement is to keep using batch apex, their will be no need of REST/any other api for updating records.
DML operations is the best way to do it.

REST Api is mostly used for communicating to Salesforce system from an external system.

Please provide little more details, may be i am not undestanding the requirement right.

Thanks