2013-04-28 72 views
2

REST最佳实践的一部分是利用响应中的链接来允许客户端从一个实体导航到另一个实体。REST超媒体/到集合的链接

例如,如果我有一个具有子帐户的客户对象类型。如果我是要求使用/customers/1客户,然后我可能会提供以下响应

{ 
    "self": "http://localhost:43002/rest/v1/customers/1", 
    "id": 1, 
    "name": "Isabella Button", 
    "number": "000001", 
    "forename": "Isabella", 
    "surname": "Button", 
    "accounts": [ 
    { 
     "self": "http://localhost:43002/rest/v1/accounts/1", 
     "id": 1, 
     "name": "Main Account", 
     "number": "000001", 
     "currency": "GBP", 
     "fromDate": "2013-01-01", 
     "toDate": "9999-01-01", 
     "createdDttm": "2013-01-01T00:00:00.000" 
    } 
    ] 
} 

注意self属性保存的链接。

但是,假设我不想在客户查询中返回帐户,也许帐户数量可能非常大,因此我不想在默认情况下返回它们。

{ 
    "self": "http://localhost:43002/rest/v1/customers/1", 
    "id": 1, 
    "name": "Isabella Button", 
    "number": "000001", 
    "forename": "Isabella", 
    "surname": "Button" 
} 

为客户账户的资源URL可以是/customers/1/accounts

但是与客户端以上客户反应将是无法发现的/customers/1/accounts链接。

是否有在指向返回资源的“子”集合的响应中提供超链接的最佳做法?

回答

5

一种做法是使用一个links元素是这样的:

{ 
    "self": "http://localhost:43002/rest/v1/customers/1", 
    "id": 1, 
    "name": "Isabella Button", 
    "number": "000001", 
    "forename": "Isabella", 
    "surname": "Button", 
    "links" : [ 
    { 
     "rel" : "http://www.yourapi.com/rels/accounts", 
     "href" : "http://localhost:43002/rest/v1/customers/1/accounts" 
    }, 
    { 
     "rel" : "http://www.yourapi.com/rels/someOtherCollection", 
     "href" : "http://localhost:43002/rest/v1/customers/1/someOtherCollection", 
     } 
    ] 
} 

或者,如果你找到更轻松地构建/读取响应,你可以把链接放在http头里。

+1

这个答案比我的好,因为在这个例子中提供了rel-value,这使得它更加稳定;-),为什么? => http://avalanche123.com/blog/2011/10/08/about-rel-attribute-from-a-web-developers-point-of-view/,http://blog.steveklabnik.com/posts/2011-12-20-write-better-cukes-with-the-rel-attribute – cproinger 2013-04-28 21:14:41

+0

@cproinger - 两个答案都很有用,但我更喜欢你的,因为它的紧凑性。在对象下提供关键/价值链接的最佳做法是我所期待的。 – 2013-04-28 21:44:44

+0

你当然不会限制链接meta对象的提供 - 当你可能需要的链接数量开始增长时,避免迭代的需要会变得很重要 – Brian 2014-06-07 13:43:44