Resteasy. Proxy client

Previously we figured out how to send requests and receive reponses. Today we’re going to go further and take a look at RESTEasy Proxy Framework. In this post we’re going to learn how to send Http Requests and receive Http Responses with RESTEasy.

RESTeasy Maven dependencies

First of all we need to add required Maven dependencies for RESTeasy Client

<dependency>
  <groupId>org.jboss.resteasy</groupId>
  <artifactId>resteasy-client</artifactId>
  <version>3.1.4.Final</version>
</dependency>
<dependency>
  <groupId>org.jboss.resteasy</groupId>
  <artifactId>resteasy-jackson2-provider</artifactId>
  <version>3.1.4.Final</version>
</dependency>

RESTEasy Proxy client.

Let’s assume we have the web service (BookService) that provides the CRUD functionality. We can describe it as an interface using JAX-RX annotations.

@Path("/api/books")
public interface BooksService {

  @GET
  @Produces(APPLICATION_JSON_VALUE)
  @Path("/")
  public List<Book> findBooks();

  @GET
  @Produces(APPLICATION_JSON_VALUE)
  @Path("/{id}")
  public Book findBook(@PathParam("id") String id);

  @POST
  @Consumes(APPLICATION_JSON_VALUE)
  @Produces(APPLICATION_JSON_VALUE)
  @Path("/")
  public Book createBook(Book book);

  @PUT
  @Path("/{id}")
  @Consumes(APPLICATION_JSON_VALUE)
  @Produces(APPLICATION_JSON_VALUE)
  public Book updateBook(@PathParam("id") String id, Book book);

  @DELETE
  @Path("/{id}")
  public void deleteBook(@PathParam("id") String id);

}

Let’s create a RESTEasy client

BooksService client = new ResteasyClientBuilder().build().target(url).proxy(BooksService.class);

and make calls to the service

Book createdBook = client.createBook(new Book("The Book 1", "Jone Doe"));
List<Book> books = client.findBooks();
Book getBook = client.findBook(createdBook.getId());
Book updatedBook = client.updateBook(createdBook.getId(), new Book("The Book 2", "Jane Doe"));
client.deleteBook(createdBook.getId());

As you can see we can access DTOs (Book, List<Book>) without marshaling/unmarshaling. We can work directly with objects.

RESTEasy Proxy Client. ClientErrorException

If your web service returns a non-success response code then RESTEasy proxy client throws exceptions - ClientErrorException which extends WebApplicationException. So you have to handle those exceptions with try-catch blocks.

try {
  client.createBook(invalidBook);
  assertions.fail("Invalid field should cause BAD_REQUEST");
} catch (ClientErrorException exception) {
  assertions.assertThat(exception.getResponse().getStatus()).isEqualTo(BAD_REQUEST.value());
}

You may also find these posts interesting: