Tech Corner - 23. August 2017
header_image

Salesforce polling versus callouts

What is polling?

Polling means actively sampling the status of a service by a client program as a synchronous activity. Polling is most often used in terms of  getting actual state. Applications typically poll for changed data periodically. In Salesforce, the client program wants to get information about created, updated or deleted Objects.

What is Salesforce callout?

Salesforce 'Callout' means some kind of Apex Web Service. Apex supports the ability to write Apex logic and expose the logic as a web service. Therefore an external application can invoke this Apex web service to perform custom logic. With 'Callouts', where Apex invokes an external web service, Apex provides integration with Web services that utilize SOAP and WSDL, or HTTP services (RESTful services). Compared to polling, 'Callouts' notify the client program and the client program can process information.

Callouts vs. Polling - main differences

Callouts are also known as webhooks, which provide your application with a way of consuming new event data from an endpoint. However, instead of sending repeated requests for new events, you provide the endpoint with a URL, usually within the endpoint UI, which your application monitors. The concept of polling is very simple: send a request for new events (specifically Create, Retrieve, Update and Delete events which signal changes in data) at a predetermined frequency. When using polling, the frequency of your polls limits how up-to-date your event data is. If your polling frequency is every 1 hour, the events returned by any poll could have happened any time in the past 1 hour. This means that any time an event occurs in the endpoint, your app will be out-of-date until the next poll. If you have frequent calls, it could consume a lot of API requests and you can reach limits really easy and soon. With callouts, this problem is eliminated. Since events are posted immediately to your monitored URL, your apps will automatically update themselves with the new data almost instantly. On the other side, you should take care of properly processing the callout, because if you might lose important data.

How to create Salesforce callout?

Login into the Salesforce. Go to the Setup. Define new Named Credential.
  1. Go to the Setup and in the Quick search field write Named Credential.

  2. Define label, name and the URL (in our case redirect url) which our webhook should hit. (For the testing purpose I recommend to use www.requestb.in to generate our testing endpoint)

  3. Click Save.

Create Apex Class.

    1. Go to the Setup and in the Quick search field write Apex Classes.
    2. Create New class and write code with your requirements.

Example sending all Cases with IDs from ids set to URL specified by 'test' Naming credential through POST method:

public class MyCase {

    @Future(callout=true)
    public static void getCalloutCasesContents(Set<ID> ids) 
        String queryString = 'SELECT Status, Priority, CaseNumber, Id FROM Case  WHERE ';
        for (ID objId : ids) {            
            queryString += 'Id=\'' + objId + '\' OR ';
        } 
        // Remove the last ' OR'        
        queryString = queryString.subString(0, queryString.length() - 4);
        sObject objDBList = Database.query(queryString);
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeObject(objDBList);
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        // set the enpoint URL to your Named Credential   
        req.setEndpoint('callout:test');
        req.setMethod('POST');    
        // Send the request, and return a response    
        req.setBody(gen.getAsString());
        HttpResponse res = h.send(req);
        System.debug(res.getBody());
    }
}
Create Apex Trigger for default Object (in our case Case).
  1. Go to the Setup and in the Quick search field write Cases and select Case Triggers.
  2. Create New class and write code with your requirements.
Example demonstrates implementation for trigger which is triggered every time new object Case is created. Then we get all the IDs (because there could be bulk operation) and use our static method from MyCase example apex class.
trigger CaseTrigger on Case (after insert) {
     Case cases = Trigger.new;
     Set<ID> ids = new Set<ID();  
     for (Case c: cases){ 
        ids.add(c.Id);          
     }
     MyCase.getCalloutCasesContents(ids);
}
Callouts bring a lot of opportunities Now, when we know, what callouts are, how to implement them, it is good to know, that they bring much more. As we mentioned before, they are defined by Apex classes using Salesforce Apex language. You can develop your own logic, JSON responses, transformations, retry mechanism, hashing or encryption of the payload response or handling specific cases if callout should be sent or not. There are also many 'Apex libraries' called 'Force.com Labs' apps available here. To sum it up, callouts define new approach, which is much more efficient and cheaper. If you develop a new app, you should definitely try it.

READ MORE