JAX-RS Client GET with Jackson

While developing your features in a project you may have to get data from a Rest-API in your Java code.
This tutorial will lead you to how to retrieve and cast data from a Rest API to your business object (or entity).

Let´s have a look at a small example doing this.

Maven Dependencies

First of all please add the following dependencies to your pom.xml.

 <dependency>
           <groupId>org.glassfish.jersey.core</groupId>
           <artifactId>jersey-client</artifactId>
           <version>2.5</version>
       </dependency>
       <dependency>
           <groupId>org.glassfish.jersey.media</groupId>
           <artifactId>jersey-media-json-jackson</artifactId>
           <version>2.5</version>
</dependency>

Maybe you now have to rebuild your project, to make the dependencies available in the IDE of your choice.

Chuck Norris, tell me a joke

We´ll start with our connection URL.
Let´s say we want to have an Application that tells Chuck Norris jokes to us. There is an API just for this.

https://api.icndb.com/jokes/random

It returns what we want to have. But we need to access this in our code, not just in the browser.

Chuck Norris Entity

We just could print out the entire payload of the Chuck Norris Rest API, but on the one side this doesn´t look nicely in the output and on the other side you mostly have to transform your GET in some kind of object.

/**
 *
 * @author javadevcorner.com
 */
public class ChuckNorris {

  
    private String type;
    private Value value;
 
    //getter and setter
}
/**
 *
 * @author javadevcorner.com
 */
public class Value {

    private long id;
    private String joke;
    private String[] categories;

    //getter and setter
}

Synchron Rest Client

package com.javadevcorner.restclientapi;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.jackson.JacksonFeature;

/**
 *
 * @author javadevcorner.com
 */
public class ChuckNorrisResource {

    private final String restAPIUrl = "https://api.icndb.com/jokes/random";

    Client client = ClientBuilder.newClient().register(JacksonFeature.class);

    private Response getChuckNorrisJoke() {
        return client
                .target(restAPIUrl)
                .request()
                .get();
    }

    protected void tellMeAJoke() {
        Response response = getChuckNorrisJoke();

        ChuckNorris joke = response.readEntity(ChuckNorris.class);
        System.out.println("My Joke is " + joke.getValue().getJoke());
    }

}

A lot of code, but don´t panic and let me explain everything to you:

Within the getChuckNorrisJoke() method we just use our client, define the source from which he has to get his data (target) and define the http operation (get, post, put, delete).

Inside the tellMeAJoke() method the response is “catched” and cast to our ChuckNorris entity. If we would miss a field (for example the id or the value), the GET would fail with an exception belonging to this missing field.

Asynchronous Rest Client

In some cases, for example when you load or store a bunch of data, it is a good idea to make this operations asynchronous. If you do so, you can move on with your business logic (or for example with your frontend) and don´t have to wait for the response of your Rest Operation.

private Response getChuckNorrisJokeAsync()
        throws InterruptedException, ExecutionException {
    Future<Response> joke = client
            .target(restAPIUrl)
            .request()
            .async()
            .get();

    Response response = joke.get();

    return response;
}

By adding the async() method in our GET operation we don´t return a response anymore. Now it becomes to a Future of type Response. The Future class holds a view more methods and is used to handle async calls.

Please ensure that you handle the two possible checked exceptions InterruptedException and ExecutionException. They can appear when you want to get the data hold in the Future object to a response.

 

Thanks for reading and have fun using the Rest Client API. 

Feel free to share

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.