Question

Part of REST best practice is to make use of links in the responses to allow clients to navigate from one entity to another.

For example if I had a customer object type which has child account. If I was to request a customer using /customers/1 then I might provide the following response

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

Note the self property holds the links.

However let's say I didn't want to return the accounts in the customer query, perhaps the number of accounts might be very large so I don't want to return them by default.

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

A resource URL for a customer's accounts could be /customers/1/accounts

However with the customer response above the client would be unable to discover the /customers/1/accounts link.

Is there a best practice for providing hyperlinks in a response that point to "child" collections of the returned resource?

Was it helpful?

Solution 2

provide a links attribute like in this example http://caines.ca/blog/programming/json-is-under-defined-for-rest/

{
 "links": {
   "self" : { "href": "{id}" },
   "up" : { "href": "{upId}" },
   "children" : { "href": "{id}/children" }
 }
}

OTHER TIPS

One practice is to use a links element like this:

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

Or, if you find easier to construct/read the response, you can put the same links as Link http headers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top