0

I am calling a method from a trigger that makes an external rest api post call. I am creating my json like this and trying to use the setBody() method, but getting an error and I am not sure how to resolve it.

The error is:

Future methods do not support parameter type of Map<Id,SObject>

I tried to play around with the way I was generating the json using the generator, but to no avail.

 @future (callout=true)
 public static void AfterUpdate(Map<Id, SObject> newItems, Map<Id, SObject> oldItems) {

 Opportunity oldOpp = (Opportunity) oldItems.get(oppId);
 Opportunity newOpp = (Opportunity) newItems.get(oppId);

 Map<String, Object> obj = new Map<String, Object>();
 obj.put('customer_id', newOpp.customer_id__c);
 obj.put('location_id', newOpp.location_id__c);

 String jsonBody = JSON.serialize(obj);

 String endpoint = 'https://xxxxxx/api/v2/xxxx';
 Http h = new HTTP();
 HttpRequest req = new HttpRequest();
 req.setEndpoint(endpoint);
 req.setBody(jsonBody);
 req.setMethod('POST');
 req.setHeader('Content-Type', 'application/json;charset=UTF-8');
 HttpResponse res = h.send(req);

}
3

Future methods only accept Apex primitive values and collections of primitives as parameters. They do not support sObject parameters or complex parameters including sObjects.

The easiest way to correct this is to break your code into a synchronous piece and pass only the serialized JSON to your @future method:

 public static void AfterUpdate(Map<Id, SObject> newItems, Map<Id, SObject> oldItems) {

 Opportunity oldOpp = (Opportunity) oldItems.get(oppId);
 Opportunity newOpp = (Opportunity) newItems.get(oppId);

 Map<String, Object> obj = new Map<String, Object>();
 obj.put('customer_id', newOpp.customer_id__c);
 obj.put('location_id', newOpp.location_id__c);

 String jsonBody = JSON.serialize(obj);

  AfterUpdate.makeCallout(jsonBody);
}

@future (callout=true)
public static void makeCallout(String body) {

 String endpoint = 'https://xxxxxx/api/v2/xxxx';
 Http h = new HTTP();
 HttpRequest req = new HttpRequest();
 req.setEndpoint(endpoint);
 req.setBody(jsonBody);
 req.setMethod('POST');
 req.setHeader('Content-Type', 'application/json;charset=UTF-8');
 HttpResponse res = h.send(req);

}

Otherwise, you'll need to use another form of asynchrony that supports sObject parameters: Queueable Apex.

  • does this mean the response from the api call has to be handled in the makeCallout() method @david-reed? – user1669296 Nov 5 at 0:16
  • @user1669296 Yes. – David Reed Nov 5 at 0:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.