Wednesday, May 22, 2013

Callout from APEX Triggers

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);
  }

}

4 comments:

  1. Just wanted to say thank you for posting this, it was really useful

    ReplyDelete
  2. Hi Suresh,

    What will happen in case Trigger.New have more that 50 records(limit of future call is 50).

    Thanks,
    Akshay

    ReplyDelete
  3. There are 2 ways that you can do.
    1. Use can parse all the records and send in a single callout
    2. Create a new temp object and using a batch you can make callout

    ReplyDelete
  4. Great post dear. It definitely has increased my knowledge Salesforce. Please keep sharing similar write ups of yours. You can check this too for Salesforce tutorial as i have recorded this recently on Salesforce. and i'm sure it will be helpful to you.https://www.youtube.com/watch?v=vp0lYTtVKhs

    ReplyDelete