cheenath.com
- Home
- Search
- About Me
- AJAX Tools
- WLS Tutorial
  - Setup
  - Introduction
  - Contact
  - FAQ
  - Useful Links
- AutoBuild
- SOAP Router


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




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

}




Step 5: Test by creating a new Account

Click Accounts Tab > New

Enter Account Name and hit save.




Step 6: Check Async Apex Jobs

Click Setup > Monitoring > Apex Job

This will display the list of Async Apex Jobs enqueued. Wait till the status of the job just submited change to completed.




Step 7: Make sure the account is updated

Go back to the account we just created. The description of this account should now be updated with the data from external server.




Problems?

If you have any problem running this sample please post a message here.

      

©2006 Manoj Cheenath