Search code examples
restcollectionsnested-object

Should REST API return nested objects or links to that objects?


What is the best practice in relation to this? Can you say that it depends on the application or is there any recommendation that indicates that one option is better than another?

The two options are as follows:

1 - Return nested objects

{
  "id": 1,
  "title": "Game A",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": [
    {"id":1,"name":"Xbox"},
    {"id":2,"name":"Playstation"}
  ]
}

2 - Return links to that objects

{
  "id": 1,
  "title": "Game A",
  "developer": "Developer DEF",
  "releaseDate": "2015-01-01",
  "platforms": [
    {"_self": "http://api.example.com/games/1/platforms/53"},
    {"_self": "http://api.example.com/games/1/platforms/34"},
  ]
}

Solution

  • "It depends".

    Caching is one of the key architectural constraints in the REST architectural style. When we cache a representation of a resource, we cache the entire representation as a single atom; when we invalidate, we invalidate the entire representation.

    Consider, for example, an auction -- the representations of the lots (the descriptions, the multi media files, the provenance data) is all slow to change; but the representation of the current high bid changes frequently. Fetching that big video every time a new bid is available is going to put a lot of unnecessary strain on the network, so you probably want a different caching policy for the video than you use for the high bid -- therefore, multiple resources.

    There a similar consideration when you are going to be re-using the same representation in a lot of different contexts -- imagine a website where each page uses the same logo and a consistent presentation style. You'll probably want to cache the logo and stylesheet, rather than embedding them in every representation that depends on them.

    In remote authoring use cases, you are more likely, I think, to embed. The problem comes about when a modification of one entity is going to cascade into another -- HTTP supports cache invalidation for unsafe requests, but it doesn't have a general purpose mechanism to announce other resources that should also be invalidated.