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?
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.
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");
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With