HAL Explorer

👉 Guide to Integrating and Using the HAL Explorer/Browser for Hypermedia APIs for Spring Boot Microservices.


What is HAL Explorer ?

HAL Explorer is a client side tool that provides a Rich UI to interact with Hypertext Application Language (HAL) based REST APIs.

When integrated with Spring Boot, particularly with Spring Data REST, it simplifies API exploration and testing.

It automatically renders links, allowing users to navigate the API through a graphical interface, which is crucial for HATEOAS (Hypermedia as an Engine of Application State) discovery. It’s a powerful tool for developers to visualize and debug RESTful services.


Table of Contents


Use Case

The primary use case is to provide a developer-friendly, interactive UI for browsing a HATEOAS-enabled REST API. It’s particularly useful for APIs built with Spring Data REST, where the framework automatically generates resources and links.

It also helps in visualizing exceptions that are formatted according to the HAL specification (e.g., using spring-hateoas’s error representation), offering more clarity than raw JSON.


Benefits

Integrating HAL Explorer significantly improves the development and understanding of HATEOAS APIs.

AdvantageBenefit
HATEOAS VisualizationMakes the HATEOAS principle tangible and easy to test, showing how clients should navigate the API.
Reduced Client EffortClients don’t need to hardcode URLs; they discover resources via links, leading to more decoupled applications.
Improved API DesignEncourages and enforces a link-driven, RESTful API design, promoting consistency and evolvability.
Self-DocumentationThe API’s structure becomes self-documented through its link relations, making resource discovery intuitive.

Features

HAL Explorer provides a rich, interactive interface for navigating HATEOAS-enabled APIs.

FeatureDescription
Interactive API NavigationAllows browsing the API by clicking on hypermedia links (_links) provided in the resource representation.
Request BuilderProvides easy-to-use forms to construct and submit various HTTP requests (GET, POST, PUT, DELETE) to the API endpoints.
JSON/HAL RenderingClearly displays the HAL-formatted responses, visually highlighting embedded resources and all available links for quick comprehension.
Debugging ToolServes as an excellent tool for quickly inspecting API responses and verifying the generated HATEOAS structure and links.

Drawbacks

While beneficial, there are trade-offs to consider when adopting HAL Explorer and HATEOAS.

DrawbackImpact/Consideration
Overhead for Simple APIsMay be overkill for extremely simple microservices or APIs without complex resource relations.
Learning CurveDevelopers and consumers unfamiliar with HAL and HATEOAS might need time to grasp the concepts fully.
Client DependencyRequires client applications to understand and process HAL links, which can complicate client-side logic compared to simple resource fetching.

Maven Dependency

Add below dependencies to enable the HAL Explorer UI.

For a complete solution, especially for exception handling, the spring-boot-starter-validation is often included to handle constraints, and spring-boot-starter-hateoas is the core for HATEOAS.

<!-- pom.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<project ...>
    ...
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-rest-hal-explorer</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        
        ...
    </dependencies>
    ...
</project>

Controller

The core change is wrapping the domain object in EntityModel and using WebMvcLinkBuilder to dynamically create links in response returned to client.

  @RestController
  public class UserResource {

    // ... Other methods and resources

    /**
     * Retrieve all users.
     * 
     * @return
     */
    @GetMapping(path = "/users")
    public List<User> retrieveAllUsers() {
      return userDaoService.findAll();
    }

    /**
     * Retrieve the users.
     * 
     * @return
     */
    @GetMapping(path = "/users/{id}", produces = {"application/json", "application/xml"})
    public EntityModel<User> retrieveUser(@PathVariable Integer id) {
      User user = userDaoService.findById(id);

      if (user == null) {
        throw new UserNotFoundException(String.format("No user exists with id : %s", id));
      }

      var link = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).retrieveAllUsers());

      final EntityModel<User> entityModel = EntityModel.of(user);
      entityModel.add(link.withRel("all-users"));
      
      return entityModel;
    }

    /**
     * Create user.
     * 
     * @param user
     * @return
     */
    @PostMapping("/users")
    public ResponseEntity<User> createUser(@Valid @RequestBody User user) {

      logger.debug("User to save : {}", user);

      var savedUser = userDaoService.save(user);

      var location = ServletUriComponentsBuilder.fromCurrentRequest().path("{id}").buildAndExpand(savedUser.getId())
          .toUri();
      return ResponseEntity.created(location).body(savedUser);
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Integer id) {

      logger.debug("Deltete the user with id : {}", id);

      userDaoService.deleteById(id);
    }
  }

Default HAL Explorer URLs

Once the dependency is added and the application is running, the HAL Explorer UI is accessible at:

        - http://localhost:8080/explorer
        - http://localhost:8080/explorer/index.html#

Security Considerations

The HAL Explorer is a powerful development tool and must be protected, especially in production or external-facing environments.

ConsiderationAction / ImplementationRationale
Restrict AccessUse Spring Security to gate access to the /explorer endpoint.Limit visibility to only users with ADMIN or DEVELOPER roles to prevent unauthorized API exploration.
Environment-SpecificControl the deployment of the HAL Explorer dependency.Disable the dependency entirely in production and non-developer environments using Spring profiles.
Input ValidationMaintain rigorous validation on all data received by your API endpoints.Prevents common vulnerabilities like SQL Injection or Cross-Site Scripting (XSS), regardless of the client (Explorer or otherwise).

CollectionModel and Spring Data REST

Spring HATEOAS provides the CollectionModel<T> class, which is a key component for representing a collection of resources in a HAL-compliant manner.

Instead of returning a raw List<T>, we’ll wrap it in CollectionModel, which allows to embed resources and add collection-level links. Spring Data REST automatically handles this when exposing repositories, making the entire collection accessible through HAL Explorer with navigation links (e.g., pagination links).

  • CollectionModel<T> is used to represent a collection, automatically serializing as an object with _links (for collection navigation) and _embedded (containing the list of individual resource models).
  • Spring Data REST is a powerful feature that automatically implements HATEOAS for repositories. By simply including the spring-boot-starter-data-rest dependency, it exposes CRUD endpoints that natively use HAL and are fully navigable through the HAL Explorer. The explorer is the perfect tool to demonstrate this automation.

Rendering Response

A representation of how CollectionModel is rendered in HAL.

graph TD
    A[Root Resource] --> B{_links};
    A --> C{_embedded};
    B --> B1(self: /api/items);
    B --> B2(next: /api/items?page=1);
    C --> C1[items: List<ItemModel>];
    C1 --> C2[ItemModel 1];
    C1 --> C3[ItemModel 2];
    C2 --> C2L{_links: self, owner};
    C3 --> C3L{_links: self, owner};

    style A fill:#f9f,stroke:#333
    style B fill:#ccf,stroke:#333
    style C fill:#cfc,stroke:#333