Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST - model state transitions

In REST - revertable DELETE a nice introduction on howto model state changes in REST was given. Basically, if you have a resource with a field status, you just put a new version of that resource with an update status field.

In this topic, I would like to extend this model. Say you have a resource which can be in two states: 1 and 2. In contrast with the simple model as described in the cited post, there are three transitions to traverse from state 1 to state 2, instead of just one.

My question is: how would you model state transitions in REST?

I myself cannot come up with an RPC-like POST, which isn't very RESTian probably:

POST http://server/api/x
     target_state=2&transition=3

This changes resource x from state 1 to state 2 by using transition 3.

like image 756
Zure Citroen Avatar asked Nov 04 '22 17:11

Zure Citroen


1 Answers

This isn't really limited to REST; it's more a basic question about state machines. The state machine should encapsulate all of the state, so that if you find yourself creating multiple transitions from one state to another, and the difference is significant, then that difference must also be captured in the state.

For example, say I have no home. I can move from the "homeless" state to the "home" state in three ways: I can rent one, I can buy one, I can steal one. Three transitions from "homeless" to "home"? Not in the world of machines. Either the differences are significant, or they're not. If they're not, then to the machine there's no point in making a distinction at all. Merely PUT the new status of "home". If they are, then we need to expand our concept of state to encompass the differences. For example:

         homeless
        A    A   A
       /     |    \
      V      |     V
possessor <--|---  renter
       A     |    /
        \    |   /
         V   V  V
           owner

I can move from homeless to possessor by stealing a house. If I squat on it long enough, I might become the owner. Or I could be homeless and rent a house, or even rent-to-own. Or I could buy one outright. All three paths get me to the "owner" state, but they use intermediate states to represent the significantly different transitions.

If you then want to represent "homeless" vs. "in a home" (possessor|renter|owner), there's no problem exposing that as a read-only, calculated resource in its own right. Just don't let anyone PUT/POST to it, since the transition is ambiguous. There's also no problem keeping the history of state transitions as an additional set of resources, if that state is significant.

like image 65
fumanchu Avatar answered Nov 09 '22 15:11

fumanchu