2

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链接。

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

4

2 回答 2

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",
      }
     ]
}

或者,如果您发现更容易构建/读取响应,则可以放置与 Link http 标头相同的链接。

于 2013-04-28T20:39:16.643 回答
2

提供一个链接属性,如本例http://caines.ca/blog/programming/json-is-under-defined-for-rest/

{
 "links": {
   "self" : { "href": "{id}" },
   "up" : { "href": "{upId}" },
   "children" : { "href": "{id}/children" }
 }
}
于 2013-04-28T20:38:15.540 回答