Saturday, December 4, 2021

How to make callout from batch class in salesforce?

 Yes it possible to do callouts from batch apex in salesforce. We have to implement the interface Database.AllowsCallouts in batch apex if we want to do callouts from batch apex.

Note: A single Apex transaction can make a maximum of 100 callouts to an HTTP request or an API call.

Here is an example below on how to do callouts from batch apex,


global class BatchApexCalloutClas implements Database.Batchable<sObject>,   Database.AllowsCallouts {

    public String query = 'Select ID,FirstName, LastName, Email, Name,Status__c  from Contact Where Status__c != null Limit 100;

    List<Contact> updatedConList = new List<Contact>();

    global Database.QueryLocator start(Database.BatchableContext BC) {

        return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List<Contact> conList) {      

        String endpointthirdpartysystem = 'Third Party End Point Here';      

        for ( integer i = 0; i< conList.size(); i++ ){

            try {                

                HttpRequest req = new HttpRequest();

                Http http = new Http();

                HttpResponse res = new HttpResponse();

                endpointthirdpartysystem = 'Your endpoint will be here' + '&pincode=' + conList[i].Pincode + '&country_code=1';

                req.setHeader('Authorization', header);

                req.setHeader('Content-Type', 'application/json');

                req.setEndpoint(endpointthirdpartysystem);

                req.setMethod('GET'); 

                if (!Test.isRunningTest()) {     

                    res = http.send(req);

                    if(res.getStatusCode() == 200 ){

                    String Response = res.getBody();

                    System.debug('Response is:' + res.getBody());

                    conList[i].Status__c = Response ;

                    updatedConList.add(conList[i]);

                    }

                    else{

                    conList[i].Status__c = Response ;

                    updatedConList.add(conList[i]);

                    }

                }                     

            }

            catch (Exception e) {      

                System.debug('Some error occured and is : ' + e.getMessage() + 'at line number: ' + e.getLineNumber() );        

            }

        }

    if(updatedConList.size() > 0){

     update updatedConList;

    }

    }

    global void finish(Database.BatchableContext BC){ }

}



No comments:

Post a Comment