HATEOAS – links are added on every single request

Issue

This Content is from Stack Overflow. Question asked by nikoloz adeishvili

I have a rest API for class Tag, and want to add a link for each object.

but the duplicate link is added on every request(which calls the findAll() method).

see the pictures below

tag after first request
tag after many requests

What should I change to make it appear only once?

Model –

public class Tag extends RepresentationModel<Tag> {
      ...
}

Controller –

@RestController
@RequestMapping("tags")
public class TagController {

private final TagService tagService;

@Autowired
public TagController(TagService tagService) {
    this.tagService = tagService;
}

@GetMapping()
public ResponseEntity<List<Tag>> findAll() {
    List<Tag> tags = this.tagService.findAll();
    List<Tag> response = new ArrayList<>();
    for(Tag t : tags) {
        t.add(linkTo(methodOn(TagController.class).find(t.getId())).withSelfRel());
        response.add(t);
    }
    return new ResponseEntity<>(response, HttpStatus.OK);
}

@GetMapping("/{id}")
public ResponseEntity<Tag> find(@PathVariable("id") Long id) {
    return ResponseEntity.ok(this.tagService.find(id));
}



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?