Category Archives: Salesforce

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')){
                    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.setBody('Information to Send');
                    response = http.send(request);
                    if (response.getStatusCode() == 200) {
                        String jsonResponse = response.getBody();
                        System.debug('Response-' + jsonResponse);
                    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, 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.

Difference between Remote Action and Action Function in Salesforce

Here are some differences between apex:actionFunction and @RemoteAction.

Remote Action Function:

  • Remote Action is an Apex annotation used to mark a method as being available for javascript remoting.
  • Remote Action can call the apex methods from any apex class.
  • Remote Action allows you to call the method from javascript yourself and retrieve the result as a javascript object for manipulation.
  • Remote Action methods are static and global, hence don’t have access to your current controller variables and methods.
  • Remote Action methods require less bandwidth, and server processing time, because only the data you submit is visible and the view state is not transferred.
  • Remote Action methods have to update the DOM manually using explicit JavaScript.
  • Remote Action methods can return data directly back to the calling JavaScript, but cannot update the page’s view state.

Action Function:

  • Action Function is a Visualforce tag allows you to invoke a controller action from the Visualforce Page asynchronously via AJAX requests.
  • Action Function can call the apex methods only from the class linked to the Visualforce page.
  • Action Function doesn’t let you get retrieve data but you can rerender the page or a specific section of the page to update it with new values from the controller instance.
  • Action Function methods are instance methods, and so can see the entire page state.
    Action Function has to transfer the page view state.
  • Action Function methods automatically update the Visualforce DOM and can refresh part or all of the page, and can provide a standard interface for showing a loading status through apex:actionStatus.
  • Action Function methods can update the page’s view state, but cannot return data directly back to JavaScript (although you can do this with some extra effort using oncomplete).

In general, apex:actionFunction is easier to use and requires less code, while @RemoteAction offers more flexibility. Moreover, @RemoteAction helps in reducing View State size and also provides you near real time transaction.