In the previous tutorial, we have developed CRUD restful web services using RESTEasy.In this tutorial, we will learn how to build a RESTful client for consuming GET, POST, PUT and DELETE RESTFul APIs.
JAX-RS 2.0 Client API Overview
JAX-RS 2.0 introduces a new client API so that you can make HTTP requests to your remote RESTful web services. It is a 'fluent' request building API with really 3 main classes: Client, WebTarget, and Response.
The Client interface is a builder of WebTarget instances.
WebTarget represents a distinct URL or URL template from which you can build more sub-resource WebTargets or invoke requests on.
There are really two ways to create a Client. The standard way or you can use the ResteasyClientBuilder class. The advantage of the latter is that it gives you a few more helper methods to configure your client. Sample code:
Client client = ClientBuilder.newClient();
... or...
Client client = ClientBuilder.newBuilder().build();
WebTarget target = client.target("http://foo.com/resource");
Response response = target.request().get();
String value = response.readEntity(String.class);
response.close(); // You should close connections!
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("http://foo.com/resource");
Update pom.xml File
Add a resteasy-client dependency in your pom.xml:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.9.3.Final</version>
</dependency>
JAX-RS RESTEasy APIs
I will be re-using the codebase written for the RESTEasy CRUD example tutorial.
package net.javaguides.resteasy.resource;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
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 net.javaguides.resteasy.model.User;
import net.javaguides.resteasy.service.UserService;
/**
* CRUD Rest APIs for User Resource
* @author Ramesh Fadatare
*
*/
@Path("users")
public class UserResource {
private UserService userService = new UserService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers() {
List < User > users = userService.findAll();
if (!users.isEmpty()) {
return Response.ok(users).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@Path("/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getUserById(@PathParam("id") Long id) {
User user = userService.fetchBy(id);
if (user.getId() != null) {
return Response.ok(user).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
boolean result = userService.create(user);
if (result) {
return Response.ok().status(Response.Status.CREATED).build();
} else {
return Response.notModified().build();
}
}
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateUser(@PathParam("id") long id, User user) {
boolean result = userService.update(user);
if (result) {
return Response.ok().status(Response.Status.NO_CONTENT).build();
} else {
return Response.notModified().build();
}
}
@Path("/{id}")
@DELETE
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("id") Long id) {
boolean result = userService.delete(id);
if (result) {
return Response.ok().status(Response.Status.NO_CONTENT).build();
} else {
return Response.notModified().build();
}
}
}
RESTEasy Client for GET, POST, PUT and DELETE RESTFul APIs
Let's create a JUnit test cases to GET, POST, PUT and DELETE Rest web services with RESTEasy:
package net.javaguides.resteasy;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.junit.Test;
import net.javaguides.resteasy.model.User;
public class UserResourceTest {
private static final String FULL_PATH = "http://localhost:8080/resteasy-crud-example-tutorial/restapi/users";
@Test
public void testListAllUsers() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client
.target(FULL_PATH);
String response = target.request().get(String.class);
System.out.println(response);
}
@Test
public void testGetUser() {
final ResteasyClient client = new ResteasyClientBuilder().build();
final ResteasyWebTarget target = client
.target(FULL_PATH + "/100");
Response response = target.request().get();
User user = response.readEntity(User.class);
System.out.println(user.toString());
response.close();
}
@Test
public void testCreateUser() {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(FULL_PATH);
Response response = target.request()
.post(Entity.entity(new User(100 L, "Amir", "amir@gmail.com"), "application/json"));
System.out.println(response.getStatus());
response.close();
}
@Test
public void testUpdateUser() {
User user = new User();
user.setName("Ram");
user.setEmail("ram@gmail.com");
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(FULL_PATH + "/100");
Response response = target.request()
.put(Entity.entity(user, "application/json"));
System.out.println(response.getStatus());
response.close();
}
@Test
public void testDeleteUser() {
ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target(FULL_PATH + "/101");
Response response = target.request()
.delete();
System.out.println(response.getStatus());
response.close();
final ResteasyWebTarget target1 = client
.target(FULL_PATH);
String response1 = target1.request().get(String.class);
System.out.println(response1);
}
}
Output
Conclusion
In this tutorial, we have created RESTEasy client to test CRUD RESTFul web services with RESTEasy. The application was deployed on Tomcat.
Comments
Post a Comment
Leave Comment