Implementing hypermedia
We learned about hypermedia and HATEOAS in Chapter 1, RESTful Web Service Fundamentals. Spring provides state-of-the-art support to HATEOAS using the org.springframework.boot:
spring-boot-starter-hateoas
dependency.
First, we need to make sure that all models returned as part of the API response contain the link field. There are different ways to associate links (that is, the org.springframework.hateoas.Link
class) with models, either manually or via auto-generation. Spring HATEOAS’s links and attributes are implemented according to RFC-8288 (https://tools.ietf.org/html/rfc8288). For example, you can create a self-link manually as follows:
import static org.springframework.hateoas.server.mvc. WebMvcLinkBuilder.linkTo;import static org.springframework.hateoas.server.mvc. WebMvcLinkBuilder.methodOn; // other code blocks… responseModel.setSelf(linkTo(methodOn(CartController.class) .getItemsByUserId(userId,item)).withSelfRel())...