How to return a record object with self-referencing link in Spring?

I have a record User:

public record User(int id, String name, int age, Boolean isMale)

then I want to create a GET method leveraging Spring HATEOAS to easily add self-referencing links to my API responses.

I created a method getUserById but I’ve been racking my brain how to add a link to a user.

I’ve figured it out how to do it:

    @GetMapping("/users/{id}")
    public ResponseEntity<EntityModel<User>> getUserById(@PathVariable("id") int id) throws IOException {
        List<User> users = getUsersFromFile();

        Optional<User> userOptional = users.stream()
                .filter(user -> id == user.id())
                .findAny();

        if (userOptional.isPresent()) {
            User user = userOptional.get();
            Link selfLink = WebMvcLinkBuilder.linkTo(UserController.class)
                    .slash("users")
                    .slash(user.id())
                    .withSelfRel();

            EntityModel<User> entityModel = EntityModel.of(user, selfLink);
            return ResponseEntity.ok(entityModel);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

Leave a Comment