How should I handle HATEOAS links and references in JSON?

20,001

Solution 1

I restarted this topic on the API-Craft google group and got some great responses.

The main advantages of the Array design are:

  • multiple links for the same relationship
  • multiple relationships for the same link without writing the link aggain
  • the ability to order the links

The map of cause has better accessibility.

As far as structure goes there are a lot of possibilities:

I guess i will go with HAL as it is the cleanest solution, the rest all look kind of... strange for json.

Solution 2

As far as structure goes, you could try looking at HAL (http://stateless.co/hal_specification.html) or JSON-LD: (http://json-ld.org/)

Solution 3

I think its so that you can offer multiple links based on the http method.

e.g.

"links": [ 
    {"rel": "sender", "method":"post", "href":"http://example.org/entity/1"},
    {"rel": "sender", "method":"put", "href":"http://example.org/entity/1"}, ... 
]

maybe you could adapt that to your idea

"sender": { 
     "href":"http://example.org/entity/1",
     "methods": ["put","post"]
}
Share:
20,001
Laures
Author by

Laures

Updated on November 10, 2020

Comments

  • Laures
    Laures over 3 years

    I'm in the process of designing a REST api and to be as RESTful as it gets. I want to incorporate HATEOAS into the json responses.

    Adding URLs to related resources is easy enough, but there was some discussion over the structure to use for those links.

    A LOT of articles I found use a structure borrowed from ATOM feeds:

    "links": [ 
        {"rel": "self", "href":"http://example.org/entity/1"},
        {"rel": "friends", "href":"http://example.org/entity/1/friends"}, ... 
    ]
    

    This raised some questions:

    • Why use an array as a container? According to a javascript developer I know, access to the links would be easier with the links as properties of an object. For example:

      "self":    { "href":"http://example.org/entity/1" }, /* (facebook uses this) */  
      "friends": { "href":"http://example.org/entity/1/friends", "type": "..."}
      
    • Is there a common json structure (beside adapting atom again) to describe references in resource properties? (for example the sender of a message).

      The reference should probably be resolved as a url again, but would it be bad to include the simple id as well? kind of like:

      "sender": { 
          "id": 12345,
          "href": "resource-uri"
      }
      

    My way of thought is that while HATEOAS makes it so a client doesn't need a lot of knowledge to use an API, I'm kind of reluctant to remove the possibility to USE that knowledge (like accessing the profile picture by building the link client-side without looking up the user first).