Tag Archives: Jersey

REST API versioning

In any client/server system, managing changes in the server can be challenging. RESTful web services are certainly no exception – especially publically available APIs. The consumers of a RESTful web service (the clients) rely on the web service to not break the contract.

Normally, the main concern will be to maintain backward compatibility. This means that if you update the server you must ensure that existing consumers will still work flawlessly.

There are several techniques to avoid disruptive changes and thus maintain compatibility – for example continuing to support existing query parameter formats, even if new ones are introduced, treating new query parameters as optional, not removing or renaming fields from resource representation bodies etc.

You should always do everything possible to avoid versioning of your web service (Cool URIs don’t change). However, even when doing your utmost, you might eventually find yourself in a situation where maintaining compatibility is impossible and some kind of versioning of your web service is inevitable.

Once you reach this point, there are two principal techniques to choose from:

  • URI versioning
  • Media type versioning

URI versioning involves including a version number in the URI. You do not necessarily have to version every resource of your service. Here is an example:

URI versioning is definitely regarded as good practice, and many well-known RESTful APIs uses URI versioning – for example LinkedIn and Groupon. However, the solution I will describe in more details is the other one: media type versioning.

Media type versioning is based on content negotiation using the HTTP headers Accept and Content-Type. The idea is that the web service, for each incoming request, has defined what version of a resource representation (aka. the media type) that it can consume and/or produce.

Likewise, when the consumer makes a request, it must include headers defining the version of the resource representation that it provides (if any) and the version of the resource representation that it expects to receive back (if any). Then the web service can easily detect whether it supports the provided/requested version of a representation. If not, it can respond with a well-defined error code.

The media types must be defined as so called vendor-specific media types. Vendor-specific media types are specialized alternatives to the standard media types such as application/xml, application/json etc. The vendor-specific media types can comprise information about the resource type (e.g. user), the version (e.g. v2) and the format (e.g. JSON):

Each GET request must comprise an Accept header defining the resource representation that the consumer expects to get back. In the below example, a request to get a representation of the user called john_doe is shown:

If the web service cannot provide the resource representation as stated in the Accept header, according to RFC2616, a response with HTTP error code 406 (Not Acceptable) shall be returned.

Each POST and PUT request providing a request body with a resource representation must provide a Content-Type header defining the resource representation. In the below example, a request to update the profile of a user called john_doe is shown:

If the web service does not accept the resource representation as stated in the Content-Type header, according to RFC2616, a response with HTTP error code 415 (Unsupported Media Type) shall be returned.

Here is a recipe on how this versioning approach can be easily applied in a Jersey (Java) based solution:

For each resource representation class, include a static field defining the vendor-specific media type. For a User class it can look for example like this:

In the web service class, use this static field when setting the media type:

The cool thing is that Jersey automatically responds with the correct HTTP error codes (406 and 415) if the media types (the versions) don’t match.

It’s my personal experience that the majority of contract-breaking changes in RESTful web services come from breaking changes in the resource representations rather than in the resource model of the web service – i.e. the URI’s (the resource identifiers) of your service. This is why, in many cases, the media-type versioning solves most of your versioning challenges – while keeping the URI’s of your service intact.

REST with Java in practice

RESTful web services are generally hyped these days – and for many good reasons: among others, the fact that they are easily consumed by almost any kind of client – browsers, mobile apps, desktop apps etc.

One technology stack for building restful services in a Java environment could comprise Jersey, Gson and Guice (nice alliteration, by the way…). Without prior knowledge to any of these technologies, me and my team managed to successfully establish a RESTful web service consumed by for example this website.

I will briefly introduce these 3 frameworks:

Jersey and JAX-RS

Jersey­ is one of several implementations of the JAX-RS interface – the Java API for RESTful web services.

Jersey provides a servlet that analyses an incoming HTTP request by scanning underlying classes for RESTful resources, and selecting the correct class and method to respond to this request. The RESTful resources are defined by decorating classes and methods with the appropriate JAX-RS annotations.

If you for example have a UserService class that you want to expose through a RESTful API, you can wrap it in a UserWebService class and decorate this class and its methods with JAX-RS annotations:

The @Path annotation specifies on which (relative) URL path this method will be invoked. The @Get annotation specifies that the http method GET has to be used and the @Produces annotation declares the format of the response.

So, the following http-request:

GET http://localhost:8080/myservice/api/user/list

will invoke the GetUserList() method, which basically is a pass-through to the UserService.getAll() method, and return a response with a list of users in JSON format.

JSON support using Gson

One of the decisions you have to make when establishing a RESTful service is which representation formats (media types) to support. Very often JSON will be the obvious choice – especially if the services are to be consumed by browser-based clients which typically use JavaScript.

In order to produce and consume JSON you need a serialization mechanism that turns a Java object into a JSON document and vice versa (under-the-hood the representation bodies will very often be POJO objects). Our choice was to use Google Gson for this purpose.

You simply need to implement the two interfaces javax.ws.rs.ext.MessageBodyWriter and javax.ws.rs.ext.MessageBodyReader, and decorate the implementing classes with the JAX-RS @Provider annotation. Here is the writer:

And here is the reader:

Guice as DI container

In a previous post I showed how to use Guice as a DI container in a Jersey application. So, what is left now is to bind the Gson writer and reader – ass well as other types, such as the RESTful resource classes – in the Guice injector:

To summarize, a well-proven technology stack for implementing a RESTful web service in Java comprises Jersey­ as the REST framework, Google Guice as the DI container to support dependency Injection and Google Gson for JSON serialization and de-serialization of the representation body objects. The service can be deployed on for example a Glassfish server.

Implementing Role-Based Authorization using Guice

Besides magically composing the entire object graph for your application, one of the main advantages of introducing a DI container is its ability to perform runtime interception. Because you are delegating the responsibility of composing objects to a 3rd party component (the DI container) you also give this container the possibility to intercept a call from the consumer to a service and execute some additional code before passing the call on to the service itself.

This is a perfect way to implement cross-cutting concerns (aspects) such as logging, validation, authorization etc. so that the underlying services don’t have to care about this and can easily follow the Single Responsibility Principle.

In this post, I will show you an example of how to implement role-based authorization using aspect oriented programming (AOP) in Guice.

The example is a RESTful web service built using Jersey­. The web service is ­using the basic authentication scheme which forces the client to authenticate itself with a user ID and a password for each request. The client must compute a Base64 encoding of <user>:<Password> and include the value in an Authorization header in the request.

The web service operates with 4 different roles: Guest, User, Editor and Admin.

The roles are meant to be hierarchical in the sense that e.g. an editor inherits all the privileges of a guest and a user. This is done by defining a RoleSet enum with an abstract method called getRoles(), which each enum has to override.

So each user does not have a role, but a role set. Through the hasRole() method it can be queried whether a user has the privileges of a particular role:

Now, to setup the role-based authorization, you need to do the following:

  1. Create a new annotation
  2. Implement the method interceptor
  3. Decorate the methods that must be protected with the new annotation
  4. Register the interceptor

Creating the annotation

First, you need to define an annotation that can be used to decorate the methods that you want protected by role-based authorization:

Implementing the interceptor

The interceptor itself is made by implementing the org.aopalliance.intercept.MethodInterceptor interface:

Through the methodInvocation variable, the interceptor has the opportunity to inspect the call: the method, its arguments, and the receiving instance. In this case, you will inspect the httpHeaders argument to get and parse the Authorization header of the http request. The Authorization header includes a Base64 encoding of <user>:<Password>, so you can decode this string and extract the username and password of the caller. The required role is extracted from the @Authorize annotation. If the calling user does not have the required role, or if the provided password is wrong, an appropriate exception is raised. Otherwise, the intercepted method is allowed to proceed.

Decorating the methods

The usage of the @Authorize annotation is straight-forward, simply decorate the method and declare the required role in the annotation parameter.

Register the interceptor

Finally, the interceptor needs to be registered. You need to create matchers for the classes and methods to be intercepted. In this case you must match any class – but only the methods decorated with the @Authorize annotation. Because you need to inject dependencies into the interceptor, use requestInjection() alongside the standard bindInterceptor() call.

As for all other calls to Guice methods, this code must reside in the bootstrapper component of the application where the whole object graphs is wired up.

Now, if a method decorated with the @Authorize annotation is called, the autorizationInterceptor will be executed before the method itself. This is Guice and AOP in action.

Dependency Injection with Java using Guice

I generally code in .NET, and in a previous post I described how to use Microsoft Unity as the DI container in a ASP.NET MVC project. Also, the whole inspiration to dig into DI came from the book Dependency Injection in .NET. However, the first “real-life” project where I decided to let DI be the driving design principle happened to be a Java-project…

Anyway, that constraint turned out to be no problem whatsoever – thanks to the fact that the above mentioned book reaches way beyond the .NET framework in the description of DI techniques, and the fact that Google provides the terrific DI container Guice for Java.

One of the golden rules of DI is not to “new” up objects. Guice introduces the @Injection annotation as an alternative to the new keyword. You can think of @Injection as the new new

To prepare for constructor injection, you have to add the @Inject annotation to your constructor:

Then, during object composition, all of the dependencies of that constructor will be automatically filled in by Guice.

You might argue that by adding this @Inject annotation, you add a dependency in your UserService class to Guice itself. However, Guice does support the standard JSR 330 annotations, so you actually don’t need to introduce Guice specific annotations in your code at all.

When composing the object graph, Guice uses bindings to map types to their actual implementations. The bindings define how dependencies are resolved during object composition. For example, to tell Guice which implementation to use for the IRepository<User> interface, you will need linked binding. The below example maps the IRepository<user> interface to the UserRepository class using the to() clause.

Note that because IRepository<User> is a generic interface, an anonymous subclass of TypeLiteral must be used in the declaration.

Now that the IRepository<user> interface mapping is in place, you can use untargeted binding to bind the concrete UserService class. An untargeted binding has no to() clause:

All the binding declarations must be gathered in the configure() method of a module. A module is a class extending the AbstractModule class:

The actual object composition is done using a so called injector:

Obviously, this kind of code shall not be scattered all over your code base. All calls to Guice types – including the injector – should be isolated in some top-level component – the composition root (bootstrapper) of the application where the whole object graphs must be wired up.

I showed in a previous post how ASP.NET MVC has built-in support for the Unity DI-container. Likewise, Jersey­­ – the Java library for building REST API’s – has seamless support for Guice so that you don’t have to manually call the getInstance() method to create objects. Guice Servlet provides a utility that you can subclass in order to register your own ServletContextListener:

To create a Guice injector you need to pass a JerseyServletModule where you are overriding the configureServlets() method. In here you must define the Guice bindings.

As most other DI containers, Guice also provides Lifetime management. The lifetime of objects can be handled through scopes. Guice supports the scopes singleton, session and request . Scopes can be configured in the bind statements using the in() clause. Here is an example of setting the scope of the user repository to singleton:

The final Guice feature I will mention is support for method interception through aspect oriented programming. This is a very powerful feature for solving cross-cutting concerns such as logging or authorization in your application. In a later post I will show how to implement role based authorization using aspect oriented programming in Guice.