0

I have the following setup

Object : CurrencyConversion__c

Field : Input_Currency__c

Field : Convert_Currency__c

I want to invoke a callout to an external webservice via a trigger (before inserting a record) in the above custom object.

I will pass "Input_Currency__c" as parameter (Id will not be passed) and the HTTP Response will contain value for "Convert_Currency__c" which I will stamp it back.

Since this webservice will be asynchronous how am I to identify the same record for which this callout was made by the time I get the response from the webservice ?

0

2 Answers 2

0

You can make a callout from the apex trigger and based on the response received you can deserialize and map it to the corresponding fields on the object to update. But make sure you might get the recursion issue inorder to update.

Trigger:

trigger CurrencyConversionUpdate on CurrencyConversion__c (before insert,before update) {
for (CurrencyConversion__c cc : Trigger.new) {
   if (any condition) {
       CurrencyCoversioncall.Integrationccupdate(cc.Id);
       System.debug('cc.Id');
     }
   }

HTTP Class to POST To an External URL:

global class CurrencyCoversioncall {
@future (callout=true)
 public static void Integrationccupdate(id ccid) {
   //Construct HTTP request and response
    //Http request method,Endpoint and setBody
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Type','application/json');
    String endpoint = 'Endpoint URL FOR External service';
    req.setMethod('POST');
    req.setEndpoint(endpoint); 
    system.debug('CC ID' +ccid);
    //SOQL to construct JSON string in set body
    CurrencyConversion__c cc=[select id,Name, Input_Currency__c from CurrencyConversion__c where id=:ccid];
    system.debug('without pretty'+JSON.serialize(cc));
    String JsonString=JSON.serialize(cc);
    req.setBody(JsonString);
    system.debug(JsonString);
    //Http response method 
    Http http = new Http();
    HTTPResponse res = http.send(req);
    System.debug(res.getBody());

  }
}
2
  • 1
    The record id is null before insert.
    – martin
    Commented Sep 6, 2015 at 6:43
  • While the effort to post the above code is appreciated, it will not work as posted on before insert as the ID is null and actually makes TWO callouts (one for insert, one for update). If for some reason it is working for the OP it is ONLY because when inserted a WFR is updating the record thus causing the before update. If there is a need for the update, then some extra work is going to have to be done to reduce multiple future methods for the same record during a given transaction.....
    – Eric
    Commented Sep 6, 2015 at 14:22
4

You do it in an after insert, passing the ID of the record to the async method. Then make call out to webservice and update the record using the ID you passed in and the results from the webservice

Not the answer you're looking for? Browse other questions tagged .