Table of contents
1.
Introduction📜
2.
HATEOAS 🧐
3.
Spring-HATEOAS 😇
3.1.
Features of Spring-HATEOAS
4.
Creating Spring-HATEOAS Project💥
5.
Frequently Asked Questions
5.1.
What is HATEOAS?
5.2.
What is Spring-HATEOAS?
5.3.
What does spring boot's @RestController annotation mean?
5.4.
Can @component take the place of @controller?
5.5.
Can we build a resource using Put rather than POST?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Implementing HATEOAS for RESTful Services

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction📜

Spring Boot is a project that uses the Spring Framework as its foundation. It makes setting up, configuring, and running simple web-based applications easier and faster. 
Spring Boot is the foundation of every developer's experience, regardless of what they're building. Spring Boot helps us to do it as quickly as possible with the least amount of configuration required upfront. 

Spring Boot

In this blog, we will learn how to Implement HATEOAS for RESTful Services in spring boot.

HATEOAS 🧐

HATEOAS stands for Hypermedia as the Engine of Application State. Hypermedia is a term used to describe content that links to other media types, such as text, movies, and photographs. The REST application has a feature that sets it apart from different network architectures. A client uses HATEOAS to engage with a network application whose application server feeds information dynamically via Hypermedia.

Spring-HATEOAS 😇

Spring-HATEOAS is an API library. These APIs can be used in combination with Spring MVC to build REST representations that comply with the HATEOAS principle.
In the Spring HATEOAS project, we concatenate the path variable to the basic URI and do not need Servlet Context. Instead, Spring HATEOAS provides three abstractions: Resource SupportLink, and ControllerLinkBuilder for URI creation. These abstractions allow us to build metadata that links to resource representations.

Features of Spring-HATEOAS

👉 It is compatible with hypermedia formats such as HAL.

👉 It provides a Link builder API that allows users to build links that point to MVC controller methods.

👉 It provides the resource representation models and model classes.

Let's say we made a GET request to localhost:3000/users/1, which results in the user id 1's details being returned. In addition, it returns a field named link that contains a URL (localhost:8080/users) to a list of all users so that consumers can retrieve users. This idea is known as HATEOAS.

Creating Spring-HATEOAS Project💥

Prerequisites: Before implementing the Delete method, you should install Java in your system and set up a project using Spring Tool Suite.
Let's implement the HATEOAS in the spring boot project.
You need to follow some steps to implement HATEOAS in the spring project.

Step 1: Open the pom.xml file and insert the spring-boot-starter-hateoas dependency.
 

<dependency>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-starter-hateoas</artifactId>  
</dependency>  
You can also try this code with Online Java Compiler
Run Code


Step 2: Open the UserResources.java file and copy the getUser() method.

Step 3: Paste the method and make the following changes:-

💢 Make a constructor of the Resource class.
 

Resource<User> resource = new Resource<User>(User)  
You can also try this code with Online Java Compiler
Run Code


Note: Import the Resource class of org.springframework.hateoas package.

💢 Use the ControllerLinkBuilder class to add a link that will return a list of all users. It helps us to link methods.

💢 Now, Import the ControllerLinkBuilder.
 

import static org.springframework.hateoas.mvc.ControllerLinkBuilder
You can also try this code with Online Java Compiler
Run Code


💢 Use the linkTo() method of the ControllerLinkBuilder class. It generates a new ControllerLinkBuilder with a mapping base annotated to the specified controller class.
 

ControllerLinkBuilder linkTo=linkTo(methodOn(this.getClass().getAllUsers());  
You can also try this code with Online Java Compiler
Run Code


💢 Include this link in the resource with the name we want to use within the HATEOAS.
 

resource.add(linkTo.withRel("all-users")); 
You can also try this code with Online Java Compiler
Run Code


💢 Instead of the user, return the resource.

💢 Change the method's return type to Resource.

After applying the modifications listed above, the UserResources.java  file should look like this:

package com.codingninjas.server.main.user;  
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;  
import java.net.URI;  
import java.util.List;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.hateoas.Resource;  
import org.springframework.hateoas.mvc.ControllerLinkBuilder;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.DeleteMapping;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;  
@RestController  
public class UserResources   
{  
@Autowired  
private UserServices service;  
@GetMapping("/users")  
public List<User> getAllUsers()  
{  
return service.findAll();  
}  
@GetMapping("/users/{id}")  
public Resource<User> getUser(@PathVariable int id)  
{  
User user= service.findOne(id);  
if(user==null)  

/*Throws Runtime Exception*/  
throw new UserNotFoundException("id: "+ id);  
 
/*To geAllUsers*/  
/*Resource class constructor*/
Resource<User> resource = new Resource<User>(user);

/*Add link to get all the users*/  
ControllerLinkBuilder linkTo=linkTo(methodOn(this.getClass()).getAllUsers());  
resource.add(linkTo.withRel("all-users"));  
return resource;  
}  

/*Method to delete a user resource*/  
@DeleteMapping("/users/{id}")  
public void deleteUser(@PathVariable int id)  
{  
User user= service.deleteById(id);  
if(user==null)  

/*Throws Runtime Exception*/  
throw new UserNotFoundException("id: "+ id);  
}  

@PostMapping("/users")  
public ResponseEntity<Object> createUser(@Valid @RequestBody User user)     
{  
User sevedUser=service.save(user);    
URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();  
return ResponseEntity.created(location).build();  
}  
}  
You can also try this code with Online Java Compiler
Run Code


Step 4: Open RestClient in VS Code, select Send Request and send the GET request to the URL: localhost:3000/users/1.

User1 data

Here, we can see that it displays both the user's data and a link to the list of all users. Now, visit the link and make another GET request. It returns a list of all users, as shown in the image below.

USERS DATA

Frequently Asked Questions

What is HATEOAS?

HATEOAS stands for Hypermedia as the Engine of Application State. A client uses HATEOAS to engage with a network application whose application server feeds information dynamically via Hypermedia.

What is Spring-HATEOAS?

Spring-HATEOAS is an API library. These APIs can be used in combination with Spring MVC to build REST representations that comply with the HATEOAS principle.

What does spring boot's @RestController annotation mean?

The @Controller and @ResponseBody annotations are already present in the Spring RestController annotation, which is a convenience annotation. Applying this annotation to a class designates it as a request handler. The Spring MVC annotation, Spring RestController, is used to build RESTful web services.

Can @component take the place of @controller?

There is no difference between @Component@Service@Controller, and @Repository. The generic annotation @Component is used to represent the component of our MVC.

Can we build a resource using Put rather than POST?

You can build or edit a resource using either POST or PUT, as both can be used to submit data. Because PUT is idempotent, it is preferred by many web developers for creating a resource on the server. No matter how often you call PUT, the resource's condition won't be in danger.

Conclusion

In this article, we have extensively discussed how to Implement HATEOAS for RESTful Services in spring boot. I hope you enjoyed reading this article on Implementing HATEOAS for RESTful Services. 

If you want to learn more, check out our articles on STS Download, Implementing DELETE Method to Delete a User ResourceTechnological Services in Ready APIWhat Is Web2Py?Why To Use Web2py?Postbacks and Internationalization in web2pyThird Party Modules In Web2pyTasks In Web2py, and  XML in Web2py.

Happy Coding!

Live masterclass