Tag Archives: Apex

Batch Apex With Webservice Callout

To make a Webservice callout in batch Apex, we have to implement Database.AllowsCallouts interface in the class definition. Here is an example to make webservice callout in batch apex.

Batch Apex:

global class AccountBatchApex implements Database.Batchable<sObject>, Database.AllowsCallouts{
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        
        for (Account acc : scope){
            if(acc.Type.equals('Customer - Direct')){
                try{
                    HttpRequest request = new HttpRequest();
                    HttpResponse response = new HttpResponse();
                    Http http = new Http();
                    
                    String username = 'YourUsername';
                    String password = 'YourPassword';
                    Blob headerValue = Blob.valueOf(username + ':' + password);
                    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
                    
                    request.setHeader('Authorization', authorizationHeader);
                    request.setHeader('Content-Type', 'application/json');
                    request.setEndpoint('Your Endpoint URL');
                    request.setMethod('POST');
                    request.setBody('Information to Send');
                    response = http.send(request);
                    if (response.getStatusCode() == 200) {
                        String jsonResponse = response.getBody();
                        System.debug('Response-' + jsonResponse);
                    }
                }
                catch(Exception){
                    System.debug('Error-' + e.getMessage());   
                }
            }
        }
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}

Note: Total number of callouts (HTTP requests or Web services calls) is 100, that means if you have one callout in your execute method you can keep batch size as 100.

URL Class in Salesforce

//Create a new account called "Test Account" that we will create a link for later.
Account acc = new Account(Name = 'Test Account');
Insert acc;

//Get the base URL.
String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
System.debug('Base URL: ' + baseURL);       

//Get the URL for the current request.
String currentReqURL = URL.getCurrentRequestUrl().toExternalForm();
System.debug('Current request URL: ' + currentReqURL);        

//Create the account URL from the base URL.
String accURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + acc.Id;
System.debug('URL of a particular account: ' + accURL); 

//Get some parts of the base URL.
System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost());   
System.debug('Protocol: ' + URL.getSalesforceBaseUrl().getProtocol());

//Get the query string of the current request.
System.debug('Query: ' + URL.getCurrentRequestUrl().getQuery());

Generate Json Data Using Apex in Salesforce

Child Class:

public class Child{

    public String Name;
    
    public Child(String name) {
        this.Name = name;
    }
}

Parent Class:

public class Parent{

    public Child[] ChildRecords;
    public String Name;
    
    public Parent(String Name) {
        this.Name = name;
        ChildRecords = new Child[0];
    }
}

Pass parameters to above class using below code:

//Select Account Id from Account Object
String accountId = '0012800001A4UgG';

//Select Account & Contact Records
Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account WHERE Id =: accountId];

//Create a parent record
Parent par = new Parent(acc.Name);

//Loop on Contacts
for(Contact con: acc.Contacts) {
    par.childRecords.add(new Child(con.Name));
}

//Get the Json data
String jsonData = JSON.serialize(par);
System.debug('JsonData-' + jsonData);

Here is the debug log snapshot of Json data:
Json Data

Note: This is the sample class. You can modify it as per your requirement.

Salesforce HTTP Status code and Error Responses

HTTP Status Code Description
200 “OK” success code, for GET,PATCH or HEAD request.
201 “Created” success code, for POST request.
204 “No Content” success code, for DELETE request.
300 The value returned when an external ID exists in more than one record. The response body contains the list of matching records.
304 The request content has not changed since a specified date and time. The date and time is provided in a “If-Modified-Since” header.
400 The request could not be understood, usually because the ID is not valid for the particular resource. For example, if you use a userId where a groupId is required, the request returns 400.
401 The session ID or OAuth token has expired or is invalid. Or, if the request is made by a guest user, the resource isn’t accessible to guest users. The response body contains the message and errorCode.
403 The request has been refused. Verify that the context user has the appropriate permissions to access the requested data, or that the context user is not an external user.
404 Either the specified resource was not found, or the resource has been deleted.
405 The method specified in the Request-Line isn’t allowed for the resource specified in the URI.
409 A conflict has occurred. For example, an attempt was made to update a request to join a group, but that request had already been approved or rejected.
412 A precondition has failed. For example, in a batch request, if haltOnError is true and a subrequest fails, subsequent subrequests return 412.
415 The entity in the request is in a format that’s not supported by the specified method.
500 An error has occurred within Force.com, so the request could not be completed. Contact Salesforce Customer Support.
503 Too many requests in an hour or the server is down for maintenance.

Recall Approval Process Using Apex In Salesforce

Sample Code:

//Object record id to recall the approval process
String recordId = '0065800000lQxxsAAC';
//Get Process Instance Work Items
ProcessInstanceWorkitem[] piWorkItems = [SELECT Id FROM ProcessInstanceWorkItem WHERE ProcessInstance.TargetObjectId = :recordId
                                         AND ProcessInstance.Status = 'Pending']; 
if(piWorkItems.size() > 0){
    //Create Process Work Item Request
    Approval.ProcessWorkItemRequest pwiRequest = new Approval.ProcessWorkItemRequest();
    pwiRequest.setAction('Removed');
    pwiRequest.setWorkItemId(piWorkItems[0].Id);
    Approval.ProcessResult result = Approval.process(pwiRequest);
}