Creating a resource in an async REST API, is it valid if my server responds with an incomplete resource with a status indicator instead of returning a temporary resource?
As an example, lets say I have a service that notarizes messages adding them in a blockchain, in order to prove their existence later (like "Proof of Existence").
The execution takes a while so its a good idea to make is asynchronous.
The user sends a POST /messages
, with the payload:
{
"message" : "Hello SO friends!"
}
The server then responds a 202 Accepted
with a body:
{
"id" : 1999283,
"message" : "Hello SO friends!",
"status" : "pending",
"block" : null,
"timestamp" : null
}
And a header Location: /messages/1999283
The resource depicted above is incomplete as it still doesn't have a block and a timestamp, and has a "pending" status.
The user will poll /messages/1999283
and will get a 200 OK
with the same json as above in the body while the server is waiting for it to be added to a block.
After some minutes, the user will poll again and get a 200 OK
along with a complete resource:
{
"id" : 1999283,
"message" : "Hello SO Friends!",
"status" : "completed",
"block" : 10029,
"timestamp" : "20181215T204012Z"
}
According to me the method you are following is correct. The core purpose of 202 Accepted status is that 'Request is accepted and the server will process it'.
Now the only problem I can see here is Until when? To answer that I recommend that you can add some calculation which will check the average time it takes to process a similar request and send them in 1st response.
{
"id" : 1999283,
"message" : "Hello SO friends!",
"status" : "pending",
"block" : null,
"timestamp" : null,
"estimatedTime" : 30 ////
}
This will have 2 advantages:
1) The user will know how much time it will take to process the request and will not poll for that much time saving few hits on the server.
2) You can have a track of repeated failures for e.g If the same request is failing multiple times then you can increase the priority for that request based on business requirements.
Apart from that, other process looks very neat.