Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build HAL links with "templated:true" using Spring-hateoas?

I'm trying to figure out how to build HAL links with templated: true. If I use

BasicLinkBuilder.linkToCurrentMapping().slash("api/public/blogs/{blog}").withRel("blog");

The { and } chars are still encoded. Any idea how to build template URL links with Spring-hateo as 0.10.0.RELEASE by its API?

Thanks.

like image 967
jiwhiz Avatar asked Apr 12 '14 15:04

jiwhiz


People also ask

What is Hal in 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.

How do you implement HATEOAS in rest spring boot?

To implement HATEOAS, we would need to include related resources in the response. Instead of Student we use a return type of EntityModel<Student> . EntityModel is a simple class wrapping a domain object and allows adding links to it. We create a new resource.

Should I use spring HATEOAS?

Spring HATEOAS provides common abstractions (representational models, a Link class, API to build links pointing to Spring MVC controllers, etc.) to ease building hypermedia driven REST APIs with Spring MVC in general. Thus, you can use it alongside Spring MVC to manually build those services.


2 Answers

I'm also wondering how this is meant to be done using the HATEOAS API. For now we've worked around it by generating the Link objects using the BasicLinkBuilder and ControllerLinkBuilder classes, and then appending templated query params into a new Link(String href) constructor. Interestingly, this builds a Link with a templated: true attribute.

We noticed that attempting to pass in values such as {blog} into the LinkBuilder classes ended in these values attempting to be replaced from values on the current request (i.e. the linkbuilder was attempting to find ?blog=value from the current request and replace value into the Link being built, and as this didn't exist was causing an exception.

Although the workaround isn't particularly nice my team hasn't been able to find any way of getting templated params into the LinkBuilders via the API without causing problems.

like image 73
Ross Taylor-Turner Avatar answered Sep 19 '22 12:09

Ross Taylor-Turner


To get brackets in links I've ended up with a bit hacky solution, but as a temporal workaround works:

  • create class:
public class BracketsLink extends Link {
    public BracketsLink(Link link) {
        super(link.getHref().replaceAll("%7B", "{").replaceAll("%7D", "}"), link.getRel());
    }
}
  • and create links using BracketsLink class:
new BracketsLink(linkTo(methodOn(MessageController.class).message("{id}")).withRel("message"))
like image 20
Maciej Walkowiak Avatar answered Sep 19 '22 12:09

Maciej Walkowiak