Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change HAL links format using Spring HATEOAS

Tags:

I'm building a Spring REST application using Spring HATEOAS (0.16.0.RELEASE) and I'd like the JSON links output to look like:

_links: {    self: {      href: "https://<ip>/api/policies/321"    } } 

while it renders like:

   "links":       [{        "rel":"self",        "href":"http://<ip>/api/policies/321"       }] 

I'm using HATEOAS Resource and ResourceAssembler.

Why do I get this format instead of the other? How can I change it?

like image 213
Tony Arad Felik Avatar asked Sep 07 '14 11:09

Tony Arad Felik


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 I use HATEOAS link?

Creating Links. Spring HATEOAS provides a Link object to store the metadata (location or URI of the resource). First, we'll create a simple link manually: Link link = new Link("http://localhost:8080/spring-security-rest/api/customers/10A");

What is HATEOAS format?

A HATEOAS request allows you to not only send the data but also specify the related actions: This example was in the JSON format. An XML format for another example would look something like this: When you send out this request to retrieve account details, you get both: Account number and balance details.

What is HATEOAS how do you implement HATEOAS for a resource?

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.


1 Answers

In order to use HAL as the message format language for our RESTful API, and enable automatic pagination, we need some configuration changes in our applicaiton. Since Spring Data and Spring HATEOAS already provides annotations for configuration, all we need is to add those annotations:

@Configuration @EnableWebMvc @EnableSpringDataWebSupport @EnableHypermediaSupport(type = { HypermediaType.HAL }) @ComponentScan(basePackages = {         "com.jiwhiz.rest" }) public class WebConfig extends WebMvcConfigurerAdapter {     @Override     public void configureContentNegotiation(ContentNegotiationConfigurer c) {         c.defaultContentType(MediaTypes.HAL_JSON);     } } 

@EnableSpringDataWebSupport will add support for pagination and @EnableHypermediaSupport(type = { HypermediaType.HAL }) will add hypermedia support. Then we set default content type to application/hal+json.

cite: Design and Build RESTful API with Spring HATEOAS by Yuan Ji

like image 75
inf3rno Avatar answered Nov 27 '22 13:11

inf3rno