Jersey Rest Client CRUD Example Tutorial

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
The source code of this tutorial available on my GitHub Repository.
Let's write Rest API and it's the corresponding client for consume same rest API.

Jersey REST Client - GET All Users Example

Jersey Rest API - Get All Users

@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 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":"[email protected]","id":100,"name":"A"},{"email":"[email protected]","id":101,"name":"B"},{"email":"[email protected]","id":102,"name":"C"}]

Jersey REST Client - GET Single User Example

Jersey Rest API code - Get User By Id

@GET
@Path("user/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") int id) {
    return Response.ok().entity(new User(100, "me", "[email protected]")).build();
}

Client Code for Above Rest API

This RESTful client code will access the 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":"[email protected]","id":100,"name":"me"}

Jersey REST Client - POST User API Example

Jersey Rest API code - Create a User

@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 for Above Rest API

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

Jersey REST Client - PUT User API Example

Jersey Rest API code - Update a User

@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 for Above Rest API

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);
}

Jersey REST Client  - DELETE User API Example

Jersey Rest API code - Delete a User

@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 for Above Rest API

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));
}

Complete example for your Reference

Maven dependencies - pom.xml 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.javadevelopersguide.jersey</groupId>
 <artifactId>jersey-crud-example</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>jersey-crud-example Maven Webapp</name>
 <url>http://maven.apache.org</url>

 <dependencies>

  <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
  </dependency>

  <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-server</artifactId>
      <version>${jersey.version}</version>
  </dependency>
  <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet</artifactId>
      <version>${jersey.version}</version>
  </dependency>

  <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-moxy -->
  <dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-moxy</artifactId>
      <version>${jersey.version}</version>
  </dependency>

  <dependency>
      <groupId>org.glassfish.jersey.inject</groupId>
      <artifactId>jersey-hk2</artifactId>
      <version>${jersey.version}</version>
  </dependency>

  <!-- Required only when you are using JAX-RS Client -->
  <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-client</artifactId>
      <version>${jersey.version}</version>
  </dependency>


 </dependencies>

 <build>
  <finalName>jersey-crud-example</finalName>
  <plugins>
   <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-war-plugin</artifactId>
       <configuration>
           <failOnMissingWebXml>false</failOnMissingWebXml>
       </configuration>
   </plugin>
   <plugin>
       <artifactId>maven-compiler-plugin</artifactId>
       <version>2.0.2</version>
       <configuration>
           <source>1.8</source>
           <target>1.8</target>
       </configuration>
   </plugin>
   <plugin>
       <groupId>org.apache.tomcat.maven</groupId>
       <artifactId>tomcat7-maven-plugin</artifactId>
       <version>2.2</version>
   </plugin>
  </plugins>
 </build>

 <properties>
     <jersey.version>2.26</jersey.version>
 </properties>
</project>

UserResource - CRUD Rest API

package com.javadevelopersguide.jersey.resources;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.javadevelopersguide.jersey.model.User;
import com.javadevelopersguide.jersey.services.UserService;

@Path("/users")
public class UserResource {

 private UserService userService = new UserService();

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public List<User> fetchAll() {
  return userService.fetchAll();
 }

 @GET
 @Path("user/{id}")
 @Produces(MediaType.APPLICATION_JSON)
 public Response get(@PathParam("id") int id) {
  return Response.ok().entity(new User(100, "me", "[email protected]")).build();
 }
 
 @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();
 }
 
 @PUT
 @Path("/user/{id}")
 @Consumes(MediaType.APPLICATION_JSON)
 public Response update(@PathParam("id") long id, User user) {
  userService.update(user);
  return Response.noContent().build();
 }

 @DELETE
 @Path("/user/{id}")
 public Response delete(@PathParam("id") long id) {
  userService.delete(id);
  return Response.status(202).entity("User deleted successfully !!").build();
 }
}

UserService 

This class serves in-memory objects for Rest API's.
package com.javadevelopersguide.jersey.services;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.NotFoundException;

import com.javadevelopersguide.jersey.model.User;

public class UserService {

 private List<User> users = new ArrayList<User>();

 public List<User> fetchAll() {

  users.add(new User(100, "A", "[email protected]"));
  users.add(new User(101, "B", "[email protected]"));
  users.add(new User(102, "C", "[email protected]"));
  return users;
 }

 public User fetchBy(long id) throws NotFoundException {
  for (User user2 :  fetchAll()) {
   if (id == user2.getId()) {
    return user2;
   }else{
    throw new NotFoundException("Resource not found with Id :: " + id);
   }
  }
  return null;
 }

 public void create(User user) {
  users.add(user);
 }

 public void update(User user) {
  for (User user2 : users) {
   if (user.getId() == user2.getId()) {
    users.remove(user2);
    users.add(user);
   }
  }
 }

 public void delete(long id) throws NotFoundException {
  // delete operation
 }
}

User Model

package com.javadevelopersguide.jersey.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {
 private long id;
 private String name;
 private String email;
 
 public User() {
  
 }
 
 
 public User(long id, String name, String email) {
  super();
  this.id = id;
  this.name = name;
  this.email = email;
 }
 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 getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}

Jersey Configuration (do not need web.xml)

Jersey application Configuration. This configures jersey so we don’t need a web.xml file.
package com.javadevelopersguide.jersey.config;

import javax.ws.rs.ApplicationPath;

// Deployment of a JAX-RS application using @ApplicationPath with Servlet 3.0
// Descriptor-less deployment
import org.glassfish.jersey.server.ResourceConfig;

@ApplicationPath("/api")
public class JerseyServletContainerConfig extends ResourceConfig {
 public JerseyServletContainerConfig() {
  // if there are more than two packanges then separate them with semicolon
  // exmaple : packages("org.foo.rest;org.bar.rest");
  packages("com.javadevelopersguide.jersey.resources");
 }
}

UserResourceClient

package com.javadevelopersguide.jersey.client;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.javadevelopersguide.jersey.model.User;

public class UserResourceClient {

 public static void main(String[] args) {
   //getUsers();
   getUser();
  // createUser();
  // updateUser();
  //deleteUser();
 }

 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);
 }

 private static void getUser() {
  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);
 }
 
 private static void createUser() {
  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));
 }

 private static void updateUser() {
  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);
 }

 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));
 }
}
The source code of this tutorial available on my GitHub Repository.

Comments