Issue
I have a rest api v1/create/order
.I need to implement the below
- Client A -> calls my create order rest api.
- I need to return an acknowledgement to the Client immediately
- Then i will do some processing in background.It will take approximate 50 to 200 sec).
- Once i complete the step 3 .i need to return the response.Result will have some computed fields that i did in step 3.
How can i implement it ? I am using Java 8 and Spring Boot framework. I can execute step 3 in background thread as it involves some parallel operations.
Solution
I think that this "use case" should be faced with asynchronous behaviour. There are no "standard solutions" to model asynchronous scenarios in REST api and the two listed above as far as I know are the only ones.
You should expose two rest endpoints
1. /v1/create/order (or even better POST /v1/order... )
2. /v1/order/{id}
the first return an id for ex. "123" that identify the resource server side or even better a link (to be more "REST") like the following :
/v1/order/123
Notice that the server should return HTTP 202 to indicate that the operation has been "accepted", and possibly add a Retry-After header to indicate that the client must call this uri not before the specified time or date (in this case 2 seconds)
HTTP/1.1 202 (Accepted)
Location /v1/order/123
Retry-After: 2
then you (after 2s) from your client periodically could invoke :
GET /v1/order/123
until you get a result.
Another solution could be to expose an api from the Client A (if it is possibile) and in this way the server could call the Client A when has finished the job. (this is possibile if Client A is itself a service). Note that although the callback solution can significantly increase the complexity of the system, in some cases it is preferable.
Answered By - obe6
Answer Checked By - Clifford M. (JavaFixing Volunteer)