Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional attributes to links using Spring Hateoas and HAL?

I'm using Spring Boot and Spring Hateoas configured with @EnableHypermediaSupport(type = HAL). While this works fine in the basic scenario I'd like the to be able to add additional attributes to the links. For example it's easy to return links that'll render links such as this:

{
   "_links":{
      "self":{
         "href":"http://localhost/"
      },
      "something":[
         {
            "href":"http://some-url.com/something1"
         },
         {
            "href":"http://some-url.com/something2"
         }
      ]
   }

What I want to do is to add more attributes to the objects in the something rel. For example:

{
   "_links":{
      "self":{
         "href":"http://localhost/"
      },
      "something":[
         {
            "name":"something1",
            "href":"http://some-url.com/something1"
         },
         {
            "name":"something2",
            "href":"http://some-url.com/something2"
         }
      ]
   }
}

What's the best way to do this (preferably using the ControllerLinkBuilder) without creating my own DTO's? I've tried creating my own subclass of Link and add field for name (and getters and setters) but they seem to be ignored.

like image 994
Johan Avatar asked Jan 15 '14 17:01

Johan


People also ask

What is Hal HATEOAS?

HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API. The HAL format is strictly coupled to HATEOAS. The main target of HATEOAS is to decouple the API Consumer from the paths used in the API.

What is the use of spring HATEOAS?

Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.

In which Spring Library is HATEOAS implemented?

The Spring HATEOAS project is a library of APIs that we can use to easily create REST representations that follow the principle of HATEOAS (Hypertext as the Engine of Application State).


1 Answers

HAL support will get a significant upgrade, so I would wait.

I don't know how you use your subclass, but basically that approach works. You must not forget the annotation on your name field. Example:

public SuperLink extends Link {
  @XmlAttribute
  private String name;

  public SuperLink(Link link, String name) {
    super(link.getHref(), link.getRel());
    this.name = name;
  }
like image 59
a better oliver Avatar answered Sep 17 '22 20:09

a better oliver