HATEOAS-如何为改变状态的链接关系建模 [英] HATEOAS - How to model link relations that change state
问题描述
遵循HATEOAS原则,即每个状态都应超链接,为改变资源状态的链接建模的最佳方法是什么?
Following HATEOAS principles that each states should be hyperlinked, what is the best way to model links that change resource state?
让我们以订单为例:
{
id : 12,
state: 'pending',
...,
links: [
...,
{
rel: 'cancel',
href: '/orders/12/cancel'
},
...
]
}
我不完全满意"/cancel" 部分-如果我可以发送带有内容的" PUT "请求,我会感觉好多了:
I am not totall happy with that "/cancel" part - I would feel a lot better if I could send "PUT" request with contents:
{
status:'cancelled'
}
但是我该如何在链接部分用"href"属性来表示呢?我想代表那里的可用操作,因为例如取消订单并不总是可能的(完成"状态).
But how do I represent that with "href" attribute in links section? I would like to represent available actions there since, for example, cancelling an order isn't always possible ('completed' state).
一种可能性是使用像'/orders/12?action = cancel'这样的URL,这有点像RPC方法,而我却缺少了一些东西.
One possibility would be to use URL like '/orders/12?action=cancel' what it kinda feels like RPC approach and that I am missing something.
另一种可能看起来最好的可能性是拥有这样的链接:
Another possibility that looks probably nicest, would be to have links like that:
{
rel: 'cancel',
href: '/orders/12/',
type: 'PUT',
values: {
state: 'cancelled'
}
}
此解决方案可能会有些冗长.
This solution maybe feels a little bit verbose.
有什么想法如何优雅地处理吗?也许有人已经解决了类似的问题"?
Any ideas how to handle that gracefully? Maybe someone has already solved similar "problem"?
推荐答案
建模资源是REST最困难的部分.严格遵守标准意味着,如果您发现自己曾经这样做过:/resource/:id/{action}
,您违反了正确使用HTTP"标准,因为理想情况下,端点应始终为名词",而不是动词"(动词是HTTP协议提供).
Modelling resources is the most difficult part of REST. Strictly adhering to the standard means if you see yourself ever doing this: /resource/:id/{action}
, you're violating the "using HTTP correctly" criteria, as your endpoints should ideally always be "nouns', never "verbs" (the verbs are what the HTTP protocol provides).
因此,尽管取决于"(即设计资源的困难部分),但通常: 对象模型状态可以视为资源本身.
So, while "it depends" (ie. the hard part of designing resources), typically: Object model states can be considered as resources themselves.
这意味着您的订单状态实际上是可以查询的资源(作为独立的/orderstatuses
资源或子资源,例如/orders/:id/status
)
Which means, your order status is actually a resource you can query (either as a standalone /orderstatuses
resource or as a sub resource eg. /orders/:id/status
)
您的应用程序状态现在可以基于订单本身的当前状态链接到状态资源.如果您的状态" 模式看起来像这样(伪):
Your Application State can now link to the status resource based on the current status of the order itself. If your 'status' schema looks something like this (pseudo):
key: 'status'
values: ['pending', 'cancelled']
然后您的应用可以PUT /order/:id/status {status:'cancelled'}
(状态良好)返回到API,然后该API会取消您的订单.这些方面的想法有点奇怪(RPC更加直观),但希望这会有所帮助.
Your app could then PUT /order/:id/status {status:'cancelled'}
(a well formed status) back to the API, which would then act to cancel your order. It's a little weird thinking in these terms (RPC is a lot more intuitive), but hopefully this helps.
这篇关于HATEOAS-如何为改变状态的链接关系建模的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!