Saturday, August 4, 2012

Consuming Django Tastypie RESTful WS with Apache HTTPClient and GSON

Creating RESTful Web Service is so simple using Django Tastypie. It's pretty much just about registering which model you want to expose. Even more amazing is that filtering feature. Read here to get more info about it.

I decided to create Java frontend to replace the existing, which uses Python Gtk. To keep with the existing look and feel I use java-gnome binding. The transition from python gtk to java-gnome is quite smooth. Java-gnome has such a good design, so the only thing that I need to for the transition is just adapting to the java paradigm, which is wonderful.

To get the JSON object from the web service, I chose Apache HTPClient, just to make things simple. I know that there are a lot of java REST client, such as restlet, jersey, etc. I stick with the simplest one.
The next thing is to figure out how to transform JSON result from the RESTful web service to POJO.  Here comes GSON to the rescue. I did not want to use python attribute name convention in my java codes. So, this one I need to solve. Fortunately, GSON comes with clever and handy feature named FieldNamingPolicy. Obviously they have really good experience in different programming language hence this feature available.

To give example on how to use it, taken from the site:


SomeObject someObject = new SomeObject("first", "second");
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
String jsonRepresentation = gson.toJson(someObject);
System.out.println(jsonRepresentation);


Awesome! That simple and you can keep the java attribute naming convention and make your java codes look good.