Jersey JAX-RS Client API Examples

1. Overview

The Jersey JAX-RS Client API, which is a fluent Java-based API for communication with RESTful Web services. The JAX-RS client API can be utilized to consume any Web service exposed on top of an HTTP protocol. Follow below standard steps to write Jersey JAX RS Client API
  • Creating and configuring a Client instance
  • Targeting a web resource
  • Identifying resource on WebTarget
  • Invoking an HTTP request
  • Complete Example
Let's write Jersey JAX RS Client for below Rest API's
HTTP GET - Collection/List of Users Example
HTTP GET - Get single User Rest API
HTTP POST - Create User Rest API
HTTP PUT - Update User Rest API
HTTP DELETE - Delete User Rest API
Let's write Rest API and it's the corresponding client for consume same rest API.

2. Jersey REST Client HTTP GET Collection/List of Users Example

Jersey Rest API code
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> fetchAll() {
 return userService.fetchAll();
}
Client Code for Above Rest API This RESTful client code will access above API and print the response in the console.
private static void getUsers() {
 Client client = ClientBuilder.newClient();

 String entity = client.target("http://localhost:8080/jersey-crud-example/api").path("users")
   .request(MediaType.APPLICATION_JSON).header("some-header", "true").get(String.class);

 System.out.println(entity);
}
Output:
[{"email":"demo@gmail.com","id":100,"name":"A"},{"email":"demo1@gmail.com","id":101,"name":"B"},{"email":"demo2@gmail.com","id":102,"name":"C"}]

3. Jersey REST Client HTTP GET Single User Example

Jersey Rest API code
@GET
@Path("user/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") int id) {
 return Response.ok().entity(new User(100, "me", "me@gmail.com")).build();
}
Client Code This RESTful client code will access above API and print the response in the console.
private void getUserClientAPI() {
 Client client = ClientBuilder.newClient();

 String entity = client.target("http://localhost:8080/jersey-crud-example/api").path("users").path("user/100")
   .request(MediaType.APPLICATION_JSON).header("some-header", "true").get(String.class);

 System.out.println(entity);
}
Output:
{"email":"me@gmail.com","id":100,"name":"me"}

4. Jersey REST Client HTTP POST User API Example

Rest API
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response create(User user) {
 // create notification
 userService.create(user);
 return Response.status(Status.CREATED).build();
}
Client Code
private static void createUserClientAPI() {
 Client client = ClientBuilder.newClient();
 WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users");

 User user = new User();
 user.setId(1);
 user.setName("Ramesh");

 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
 Response response = invocationBuilder.post(Entity.entity(user, MediaType.APPLICATION_JSON));

 System.out.println(response.getStatus());
 System.out.println(response.readEntity(String.class));
}
Output:
201

5. Jersey REST Client HTTP PUT User API Example

Rest API
@PUT
@Path("/user/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(@PathParam("id") long id, User user) {
 userService.update(user);
 return Response.noContent().build();
}
Client Code
private static void updateUserClientAPI() {
 Client client = ClientBuilder.newClient();
 WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users")
   .path("user/1");

 User user = new User();
 user.setId(1);
 user.setName("Ramesh");

 Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
 Response response = invocationBuilder.put(Entity.entity(user, MediaType.APPLICATION_JSON));

 String userJson = response.readEntity(String.class);

 System.out.println(response.getStatus());
 System.out.println(userJson);
}

6. Jersey REST Client HTTP DELETE User API Example

Rest API
@DELETE
@Path("/user/{id}")
public Response delete(@PathParam("id") long id) {
 userService.delete(id);
 return Response.status(202).entity("User deleted successfully !!").build();
}
Client Code
private static void deleteUser() {

 Client client = ClientBuilder.newClient();
 WebTarget webTarget = client.target("http://localhost:8080/jersey-crud-example/api").path("users")
   .path("user/100");

 User user = new User();
 user.setId(1);
 user.setName("Ramesh");

 Invocation.Builder invocationBuilder = webTarget.request();
 Response response = invocationBuilder.delete();

 System.out.println(response.getStatus());
 System.out.println(response.readEntity(String.class));
}

7. Conclusion

In this post, we have developed Jersey JAX-RS Client API for below API'S:
HTTP GET - Collection/List of Users Example
HTTP GET - Get single User Rest API
HTTP POST - Create User Rest API
HTTP PUT - Update User Rest API
HTTP DELETE - Delete User Rest API
You can learn more on the complete Jersey Rest Developer Guide
All the code of this article is available over on Github. This is a Maven-based project, so it should be easy to import and run as it is.


Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments