Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous callback from web api controller

I'm very new to Web API and I have an unusual pattern that I need to implement. In the Post method of my controller, it is to take an object which includes a CallbackURL. It will then immediately return an HTTP response to the caller. Afterwards, it will use a 3rd party, off-site API to perform some work with the object. Once that work is done, the controller is to post the results of that work to the CallbackURL.

However, I do not know how to implement this in Web API. Once I return the HTTP response, the controller's lifecycle is over, correct? If so, how do I perform the work I need to do after I return the response?

like image 807
Joshua Dixon Avatar asked Jan 30 '26 07:01

Joshua Dixon


2 Answers

If you only need to post results to a url and not to the client that initiated the call, you could possibly do something as easy as this:

public string MyAPIMethod(object input)
{
    Task.Factory.StartNew(() =>
    {        
        //call third-party service and post result to callback url here.        

    });

    return "Success!";
}

The api call will return right away, and the Task you created will continue the processing in a different thread.

like image 149
Jason P Avatar answered Feb 01 '26 22:02

Jason P


Creating a task to finish up the request (as suggested by Jason P above) will most likely solve the problem, thread-safety provided. However that approach might hurt the performance of your Web service if calls to the 3rd party API take a significant amount of time to complete and/or you are expecting many concurrent clients. If that was the case, your problem seems to be the perfect candidate for a service pattern called "Request/Acknowledge/Callback" (also "Request/Acknowledge/Relay"). Using that pattern, your Web API method will just store each request (including the callback URL) into a queue/database and return quickly. A separate module (possibly running on more than one machine, depending on the number and complexity of the tasks) will take care of completing the tasks, and subsequently notifying completion through the callback URL (please see http://servicedesignpatterns.com/ClientServiceInteractions/RequestAcknowledge).

like image 33
Ruben Ramirez Padron Avatar answered Feb 01 '26 22:02

Ruben Ramirez Padron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!