+ Start a Discussion
Jancy MaryJancy Mary 

Guidance to use @future annotation.

Hi guys,
I worked on a requirement where I defined a web service on my org with the help of Apex REST, now I need it to be defined Asynchronous. I wrote the below apex class. I tested it using postman(google) client. It returns perfect result. But not sure about the Asynchronous which I defined. Can anyone guide me here if I am wrong.
Thank you in advance

global with sharing class MyUpdatedContacts


global static List<Contact> recentUpdatedCon(){
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
List<Contact> Contact;
String contactId= req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
Contact=[select Id, Name from Contact where SystemModStamp >=LAST_N_DAYS:30];
return Contact;

 @future (callout=true)
public static void firstTest(){
Daniel BallingerDaniel Ballinger
What do you mean by needing an asynchronous definition?

Do you want the REST service to be async? Wouldn't that be a problem for the calling code.

Using the @future (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_future.htm) annotation on firstTest() means it will be be executed asynchronously from the current Apex transaction. It will start and run sometime after the current execution has completed. You could start it from a REST GET request, but you couldn't return any results from it.
Jancy MaryJancy Mary

Hi Daniel,

I am new to the integration part, I wanted to write a web service on salesforce side to invoke it from my client, after some research I chose Apex REST as best option, but then I was asked to make this 'REST service to be async'. I am not sure the @future annotation which I used is in the correct form/logic.


I recently also came across that if we use (callout=true) along with the future annotation then we need to define the response in the same method which is annoted, not sure how far this information is correct. Could you please help me by modifying the above code if it needs to be and help my code work. Or may be you can guide me if anything has to be changed to make it logical.


Thank you very much for your help. 


Daniel BallingerDaniel Ballinger
Hi Jancy,

I'm not aware of any direct native support from Salesforce for async REST. If you want your Apex method to return anything then you are going to need to do it syncronously. If you don't need to return anything, they you could do an @future call to do the processing later.

If you are in Visualforce calling the web service you could look at using a Continuation. See Make Long-Running Callouts from a Visualforce Page (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_continuation_overview.htm).

Can you clarify why you need the REST service to be async? Can the calling code not handle it?