Monday, May 16, 2011

A simple (REST) web service client in Scala

For the purpose of creating a nice API for my new project Caligo (more on this in a future blog post), I was looking for a simple solution to access REST web service in Scala.

My requirement was simple: access an HTTP web service, and exchange data with him using the JSON format.

During my experiment I came across theses two nice Scala libraries:

Dispatch seems to be the only available HTTP client for Scala today, and since it's based on the Apache's one no need to worry about his reliability or compatibility.

SJSON was choose against Lift-JSON due to it's better handling of reflection on beans, both of them did a great job on case classes, but only SJSON was effective on beans (was mandatory for me since I must do polymorphism on my model and case classes do not support this).

Lift-JSON support of beans (thru reflection) must be improved on the version targeting Scala 2.9

Here is a sample usage of the frameworks, both of them are easily integrated, and using the power of the Scala syntax a full client request doesn't take that much code to be implemented (in this case 4 lines of code, model included):