Spring Boot has a specific starter for HATEOAS called spring-boot-starter-hateoas. We need to add it to the pom.xml file.
The following code snippet shows the dependency block:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
One of the important dependencies of spring-boot-starter-hateoas is spring-hateoas, which provides the HATEOAS features:
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
Let's enhance the retrieveTodo resource (/users/{name}/todos/{id}) to return a link to retrieve all todos (/users/{name}/todos) in the response:
@GetMapping(path = "/users/{name}/todos/{id}")
public Resource<Todo> retrieveTodo(
@PathVariable String name, @PathVariable int id) {
Todo todo = todoService.retrieveTodo(id);
if (todo == null) {
throw new TodoNotFoundException("Todo Not Found");
}
Resource<Todo> todoResource = new Resource<Todo>(todo);
ControllerLinkBuilder linkTo =
linkTo(methodOn(this.getClass()).retrieveTodos(name));
todoResource.add(linkTo.withRel("parent"));
return todoResource;
}
Some important points to note are as follows:
- ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveTodos(name)): We want to get a link to the retrieveTodos method on the current class
- linkTo.withRel("parent"): Relationship with the current resource is parent
The following snippet shows the response when a GET request is sent to ;http://localhost:8080/users/Jack/todos/1:
{
"id": 1,
"user": "Jack",
"desc": "Learn Spring MVC",
"targetDate": 1484038262110,
"done": false,
"_links": {
"parent": {
"href": "http://localhost:8080/users/Jack/todos"
}
}
}
The _links section will contain all the links. Currently, we have one link with the relation parent and href ; as http://localhost:8080/users/Jack/todos.
HATEOAS is not something that is commonly used in most of the resources today. However, it has the potential to be really useful in reducing the coupling between the ;service provider and the consumer.