Tuesday, 29 April 2014

Callout from APEX Triggers

This tutorial shows how to make HTTP callout from an APEX trigger using Future method. 

Step 1: Create Apex Class

First step is to create an apex class. After you login, click on Setup > Develop > Apex Classes > New. 

Step 2: Write future method

Write future method that calls external service.
public class AccountUpdater {

  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateAccount(String id, String name) {

    //construct an HTTP request
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://cheenath.com/tutorial/sfdc/sample1/data.txt');
    req.setMethod('GET');

    //send the request
    Http http = new Http();
    HttpResponse res = http.send(req);

    //check the response
    if (res.getStatusCode() == 200) {

      //update account
      Account acc = new Account(Id=id);
      acc.Description = res.getBody();
      update acc;
    } else {
      System.debug('Callout failed: ' + res);
    } 
  }
}


Step 3: Add external server to Remote Sites

Click Setup > Security Controls > Remote Site Settings > New Add external site name and endpoint URL
Site:cheenath
endpoint url:http://cheenath.com/

Step 4: Create APEX trigger

Click Setup > Customize > Accounts > Triggers > New
And create the following trigger:
trigger descriptionUpdater on Account (after insert) {

  System.debug('Making future call to update account');
  for (Account acc : Trigger.New) {
    //Call future method to update account
    //with data from external server.
    //This is a async calls, it returns right away, after
    //enqueuing the request.

    AccountUpdater.updateAccount(acc.Id, acc.Name);
  }

}