Tuesday, January 5, 2016

RESTful Web services - How do you implement HATEOAS ?

Look at the code below :-

package per.sample.rest.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import per.sample.rest.bean.User;
import per.sample.rest.bean.UserServiceResponse;

@Path("/hateoas")
public class HATEOASExample {

/**
* HATEOAS ("Hypermedia as the Engine of Application State") is an approach to building RESTful web services,
* where the client can dynamically discover the actions available to it at runtime from the server.
* All the client should require to get started is an initial URI, and set of standardized media types.
* Once it has loaded the initial URI, all future application state transitions will be driven by the client
* selecting from choices provided by the server.
* @param userName
* @param age
* @param uri
* @return
*/
@GET
@Path("/hateoassample/{name}/{age}")
@Produces(MediaType.APPLICATION_JSON)
public UserServiceResponse getUserDetails(
@PathParam("name") String userName, @PathParam("age") String age,
@Context UriInfo uri) {
UserServiceResponse resp = new UserServiceResponse();
resp.setUserName(userName);
resp.setAge(age);
resp.setRel("self");
resp.setUrl(uri.getAbsolutePath().toString());
return resp;
}

@GET
@Path("/hateoassample/{name}/{age}/{address}")
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("name") String userName,
@PathParam("age") int age, @PathParam("address") String address,
@Context UriInfo uri) {
User user = new User();
user.setId(1);
user.setAge(age);
user.setAddress(address);
user.setName(userName);
user.setRel("/users");
user.setUrl(uri.getAbsolutePathBuilder().build(user).toString());
return user;
}
}

No comments:

Post a Comment