Implementing HATEOAS for RESTful Services
HATEOAS acronyms for Hypermedia as the Engine of Application State. The term hypermedia refers to content that contains a link to other forms of media like images, movies, and text. It is a component of the REST application that distinguishes it from other network architecture. Using HATEOAS, a client interacts with a network application, whose application server provides information dynamically through Hypermedia.
Spring-HATEOAS is the library of APIs. We can use these APIs for creating REST representations that follow the HATEOAS principle while working with Spring MVC.
In the Spring HATEOAS project, we do not require Servlet Context and concatenate the path variable to the base URI. Instead of this, Spring HATEOAS offers three abstractions for creating the URI: ContrrollerLinkBuilder, Link, and Resource Support. We can use these abstractions to create metadata, which associates with the resource representation.
Spring Boot does the following tasks:
Suppose, we have requested a GET request for localhost:8080/users/1, it returns the details of user id 1. Along with this, it also returns a field called link that contains a link (localhost:8080/users) of all users so that consumers can retrieve all the users. This concept is called HATEOAS.
Let's implement the HATEOAS in the project.
Step1: Open the pom.xml and add the spring-boot-starter-hateoas dependency.
Step 2: Open UserResource.java and copy the retrieveUser() method.
Step 3: Paste the method and make the following changes:
Remember that import the Resource class of org.springframework.hateoas package.
methodOn() is a wrapper for DummyInvocationUtils.methodOn(class, Object) to be available in case you work with the static import of ControllerLinkBuilder.
withRel(String rel) is the method that creates the link built by the current builder instance with the given rel. The parameter rel must not be null.
After making the above changes the UserResource.java file look like the following:
Step 4: Open the REST client Postman and send a GET request.
Here we can see that it returns the user along with the link to access all-users. Now click on the link and send a GET request again. It returns the list of all users, as shown in the following image.