开发者

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜