Tuesday, May 17, 2016

PUT to update a resource state

It is common that a resource's behavior changes according to its state. A online survey is such a resource. A survey can have two states: idle and active. In idle state, a survey does not accept user inputs, and it does in active state.  The state transition can be seen in the follow figure.

Survey state transition diagram
Now if we want to expose the status of the survey as a resource, then we will have the following interfaces.

Method URL Details
GET /surveys/:id/state Get the current state of a survey
PUT /surveys/:id/state Set the state of a survey

The PUT request can have the state to set in the request body. The response can be 200 with the set result. The response can also be 4xx, if the client has erred. The error can be 403 forbidden, 404 survey not found, or 409 conflict if the state to set is not supported.

I am surprised to see that POST was used to set survey state in Google's survey API. The interfaces are:

Method URL Details
POST /surveys/:id/start set the survey to be active
POST /surveys/:id/stop set the survey to be idle

This design has two problems compared to the previous design:
  1. /surveys/:id/start and /surveys/:id/stop are not resources; and
  2. POST is not idempotent, but PUT is.