Programming & Development / April 19, 2025

πŸ“Ž Adding HATEOAS to DTOs in Spring Boot (With Java Examples)

Spring HATEOAS tutorial add links to DTO Java RepresentationModel example hypermedia Spring Boot REST API HATEOAS example DTO with links Java HATEOAS controller integration self link spring boot

πŸ“Œ What Is HATEOAS?

HATEOAS stands for Hypermedia as the Engine of Application State, a key constraint of RESTful services. It allows a client to interact with a REST API entirely through hypermedia links provided dynamically by the server.

Instead of hardcoding endpoint URIs, the client discovers available actions via embedded links in the API response.

🎯 Goal

Enhance a Java DTO to include navigable links using Spring HATEOAS. We’ll embed links like:

  • self: link to the current resource
  • all: link to the collection of similar resources
  • (Optional) update, delete, or related resource links

🧱 Step-by-Step Setup

βœ… 1. Add spring-hateoas Dependency

In pom.xml:

xml

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

βœ… 2. Create a DTO Extending RepresentationModel

This allows the DTO to hold hypermedia links.

java

import org.springframework.hateoas.RepresentationModel;

public class CollegeDTO extends RepresentationModel<CollegeDTO> {
    private Long id;
    private String name;
    private String website;

    // Getters and setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getWebsite() { return website; }
    public void setWebsite(String website) { this.website = website; }
}

βœ… 3. Add Links in Controller Using linkTo and methodOn

java

import org.springframework.hateoas.Link;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;

@RestController
@RequestMapping("/colleges")
public class CollegeController {

    @GetMapping("/{id}")
    public CollegeDTO getCollegeById(@PathVariable Long id) {
        CollegeDTO dto = new CollegeDTO();
        dto.setId(id);
        dto.setName("Sample College");
        dto.setWebsite("https://samplecollege.com");

        // Self link
        dto.add(linkTo(methodOn(CollegeController.class).getCollegeById(id)).withSelfRel());

        // Link to all colleges
        dto.add(linkTo(methodOn(CollegeController.class).getAllColleges()).withRel("all-colleges"));

        return dto;
    }

    @GetMapping
    public List<CollegeDTO> getAllColleges() {
        return List.of(); // Mocked for simplicity
    }
}

πŸ§ͺ Sample JSON Response

json

{
  "id": 1,
  "name": "Sample College",
  "website": "https://samplecollege.com",
  "_links": {
    "self": {
      "href": "http://localhost:8080/colleges/1"
    },
    "all-colleges": {
      "href": "http://localhost:8080/colleges"
    }
  }
}

πŸ” Why Use HATEOAS?

BenefitDescriptionπŸ”Ž DiscoverabilityClients discover available actions via links.🧭 Self-navigationNo need to hardcode endpoint paths on client side.πŸ“– Self-documentingThe API response describes itself.πŸ”„ MaintainabilityChanges to routes are handled server-side, not in clients.

βš™οΈ Pro Tips

  • βœ… Use RepresentationModel<T> for single DTOs.
  • 🧾 For collections, use CollectionModel<T> or PagedModel<T>.
  • 🧹 Keep links dynamic using WebMvcLinkBuilder instead of hardcoding.
  • πŸ”’ Secure link generation (e.g., skip unauthorized actions) if needed.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex