Java – Rest Client API design and implementation (with RestEasy)

apiclientjavarest

I am working on a design to create a generic rest client for our application for current and future integration's with multiple services (different external systems). Following is a high level diagram

High level design

I am thinking of creating a RestClient per external host, and Store them in a Map with Service name as Key and RestClient as value. Following is my RestClient(will be cached) class that wraps ResteasyWebTarget.

public class RestClient {
    private ResteasyWebTarget target;

    @Singleton
    public class RestClientRepository {
        private final Map<String, RestClient> repository = 
            new ConcurrentHashMap<String, RestClient>() 

My default implementation will be using RestEasy. As my client code will be part of a webapp(multihtreaded environment). I will be using PoolingClientConnectionManager

ClientConnectionManager cm = new PoolingClientConnectionManager();
HttpClient httpClient = new DefaultHttpClient(cm);
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
ResteasyClient client = ((ResteasyClientBuilder) ResteasyClientBuilder
  .newBuilder()).httpEngine(engine).build();

Is there a better solution than this approach?

Best Answer

In the first place it seems to be right, but I think you want to hide these implementation details. Ask your self: where is the difference between a local database and some remote data servers?

You probably want to have a been for each resource like User and a store like UserStore. Each store has some methods for interaction like:

public User getUser(String, String)
public User getUserById(long)
public void updateUser(User) throws ...
public void deleteUser(User)
public void createUser(User)

This hides the implementation details of your REST API. And the details of caching locally and so on (if you want to cache locally you have to synchronize the data and doing synchronization correctly is very hard to solve!)

Related Topic