RESTful API – Best Way to Implement Status Changes and Events

client-serverrest

For example I need to update the status of a "Purchase Order" from "Draft" to "Sent". What's the best way of doing this?

Do I just the update the status field in the client side and then just POST the whole entity to /purchase_order/1

And how about events? For example I want to trigger that all Purchase Orders be set to "Sent", what's the best practice for this, in terms of the endpoint and the responsibilities of the client?

Best Answer

If you google "REST partial update" you will get a lot of opinions.

Having said that I'll give you my thoughts.

A PUT should be used for a full update of a resource so only changing one parameter you are better off PUTting to /purchase_order/1 a recent result of a GET to /purchase_order/1 with the status field changed from draft to sent.

Depending on the semanics of your system you might consider a draft and a sent item to be different resources (with different primary keys) and so a GET to /purchase_order/1, change the status, then POST to /purchase_order/ (although I'm guessing that in this case purchase orders don't become new purchase orders when thir status changes).

Another option would be to send a PUT to /purchase_order/1/status with a value of sent, this could then be interpreted on the server side as an update to the sub resource status of the resource purchase_order. You could even return 303 pointing back at the /purchase_order/1 resource to let the client know that a different resource than they interacted with has changed and where to find that resource.

You could consider the PATCH verb but if you follow the semantics properly then you shouldn't just send the requested state, but rather a content-type that you specify that lists a set of operations you wish to be applied.

If an action is going to have side effects then you need to make this clear in your API. So be careful when using PUT, which is designed to be idempotent.