1

Let's say I have a REST API adhering to basic HATEOAS principles. Items belong to a User.

GET /item/13

{ 
  id: 13,
  name: 'someItem',
  type: 'someType',

  _links: [
    {
      rel: 'user',
      href: '/user/42'
    }
  ]        
}

Now I need a way to change the user for a given item. Using either a PUT or a PATCH, which is the preferable way of performing that modification?

  1. Establish the new relation by setting the id of the new linked resource as a simple property in the JSON body

    PATCH /item/13
    {
      userId: 43
    }
    
  2. Establish the new relation by having the client pass the link itself as the input

    PATCH /item/13
    {
      _links: [
        rel: 'user',
        href: '/user/43'
      ]
    }
    

I usually think of links as read-only representations of relations stored in other formats (such as id:s to other resources), returned from GET calls. It doesn't feel very natural to me to have links as input to POST/PUT/PATCH calls, and the fact that links is an array makes it even stranger (should you be able to update all links? One single link?), but I have seen it suggested in various articles. Is there a best practice? What would be the benefits of using the links approach?

4

1 回答 1

4

REST 的重点是(至少其中之一)是通过标准界面使所有内容都可见。换句话说,如果“关系”是一件事,那么它也应该有自己的资源。

API 也应该更具描述性。这可能是主观的,我不知道您的模型/设计的所有细节,但“项目”没有“链接”。相反,“物品”可能只有一个“所有者”。如果是这种情况,它可能看起来像:

GET /item/123/owner

因此,发布或放置用户的 URL(或一些简单的表示)会“改变”项目的所有者。可能不允许删除所有者,具体取决于模型是否允许未拥有的项目。

请注意,在这种情况下,“/item/123”下的表示必须链接到“/item/123/owner”,因为客户端只遵循它从服务器获取的链接。

所以,想想什么是重要的“东西”,所有这些都应该有资源。此外,尝试添加尽可能多的“意义”/语义。该关系不应称为“用户”,而应称为“所有者”(或模型中的任何含义)。

于 2016-01-26T10:02:09.633 回答