HATEOS

Introduction

  • HATEOS (Hypermedia as the Engine of Application State) can used in API end point and display relevant api end point

Configuration

  • porn.xml

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

Model

  • Extend the modal of HATEOS

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.hateoas.RepresentationModel;
import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo extends RepresentationModel<UserInfo>{
    private Long id;
    private String username;
    private String email;
    private List<String> roles = new ArrayList<>();
}

Controller

// Add Reference to another api end point
@GetMapping(value = "/users")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public List<UserInfo> getAllUser(){
    List<UserInfo> userInfoList  = userService.getUserList();
    for (UserInfo userInfo : userInfoList) {
        Link selfLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).getUserInfoById(userInfo.getId())).withRel("Self");
        userInfo.add(selfLink);
    }
    return userInfoList;
}

@GetMapping("/user/{id}")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public UserInfo getUserInfoById(@PathVariable Long id){
    UserInfo userInfo = userService.getUserInfoById(id);
    Link allLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).getAllUser()).withRel("All");
    userInfo.add(allLink);
    return userInfo;
}

Result

  • The data format will be application/hal+json

Last updated

Was this helpful?