Introduction to Hateoas in Spring Rest

Go Back to Course Outline Repositories

Go Back to Course Outline

To enable HATEOAS, spring-boot-starter-hateoas dependency must be added to your pom.xml file.

HATEOAS or Hypertext as the Engine of Application State is a guideline for the client to navigate to the relevant information for a given resource. For example, if you have an entity resource, it makes sense to also return the list URL for that entity as well as the link for the entity itself.

[open CategoryController class]
There are 2 main classes that we need to remember when implementing HATEOAS, Resource, and Resources. Resource must be parameterized with the entity that it is handling. For example Resource. This will return the category object plus the related links like self and list. 

In the one() method, the category object is wrapped into a Resource object and links are set before it is returned.

[show one() method]

As the name implies, Resources takes on an array of Resource<> eg. Resources>.

[show all() method]

Now start the Spring boot application.

[run oneCode and all tests in Postman]

[open categoryResourceAssembler class]

If you will notice in our class we have this categoryResourceAssembler class. It contains a utility function that wraps an entity in a Resource object. It’s really important as it saves you a lot of time writing the common links for a given entity.

There are times when we simply want a subset of the entity’s field in the response and that’s what we will present in the next video. So see you there!


spring-rest 8428387379271265804

Post a Comment Default Comments