Before getting into the declarative offerings from the Jersey framework to build HATEOAS APIs, let's see what is there in the JAX-RS API specification for solving this use case. JAX-RS 2.1 has the basic API support for representing hypermedia links with resources.
Let's take an example to understand the APIs provided by JAX-RS for building resource links. Consider the following REST resource class method, which returns a list of department resources:
//Rest of the code is omitted for brevity @GET @Path("departments") @Produces(MediaType.APPLICATION_JSON) public List<Department> findAllDeprtments(){ //Finds all departments from database List<Department> departments = findAllDepartmentEntities(); return departments; }
Let's see how we can add hypermedia links for accessing employee resources in each department resource representation returned by the preceding method. This link can be traversed by a client to read the employees for a department. To add a link, you use the javax.ws.rs.core.Link API. The entity provider components that come with the JAX-RS implementation will automatically convert the links to the appropriate media type representation at runtime:
//Other imports are omitted for brevity import javax.ws.rs.core.Link; import javax.xml.bind.annotation.adapters.XmlAdapter; @XmlRootElement public class Department { private Short departmentId; private String departmentName; private Integer managerId; private Short locationId; Link employeesLink; @XmlElement(name = "link") @XmlJavaTypeAdapter(XmlAdapter.class) public Link getEmployeesLink() { employeesLink = Link.fromUri("{id}/employees") .rel("employees").build(departmentId); return employeesLink; } //Rest of the getters and setters are omitted for brevity }
Here is a quick overview of the APIs used in this example:
- In the preceding code snippet, the Link.fromUri() method call creates a new hypermedia link builder object, which is an instance of javax.ws.rs.core.Link.Builder. This Builder instance is used for building hypermedia links.
- The rel() method on the Builder instance lets you set the name for the link field present in the resource. This example sets the link relation as employees.
- You can also set certain attributes on a link object, such as the media type, title, or parameter, by calling the respective methods, such as type(), title(), or param(), defined on the Builder instance.
- The final build() method results in building the hypermedia link with the supplied values. In this example, the build() method will replace the param {id} template present in the URI, with the supplied departmentId parameter.
Here is the sample JSON representation generated for the Department resource that we discussed in this example:
[{"departmentId":300,"departmentName":"Administration", "link":{"href":"300/employees","rel":"employees"}, "locationId":1700,"managerId":200} ...]