Thursday, March 13, 2014

A very simple example of spray-client usage

This post is about Scala and how to send REST/HTTP request with the spray-client API. I wrote this because the official tutorial here was leaving out some details in my opinion. I'll start with the dependencies required to compile an example program similar to the tutorial on the spray page. If you worked with Scala you've probably also used sbt (Simple Build Tool) which is a great tool to manage dependencies. If configured correctly it does a lot of things for you, but I'll show an alternative and manual way to include the libraries needed for this example program.1

The first set of dependencies are, the links will take you to downloads pages on mvnrepository.com

akka-actor 2.2.x
spray-can
spray-http
spray-httpx
spray-util

In addition to the above a few more jars are needed

parboiled-core
parboiled-scala
spray-client
spray-io
typesafe-config (part of Scala distribution, i.e. if you have Scala installed you already have this jar)


With these jars on the build path we can begin with the example code. The code declares a trait (or an interface) to a Webclient with a get method, a class implementation of the trait and an application object. The application object starts the Akka system, which spray is built on, creates the client and sends a HTTP GET request to an URI. At some time in the future the reply is received. This is everything needed and is shows the conciseness of Scala and Spray in a quite eloquent manner.

There is of course much more to spray, and if futures, akka and actors are not familiar, a very smart next move is to study them before continuing with spray. An introduction on Scala Futures and Akka should not take much time and will make you a lot more productive with spray.



1. When writing this I was on a network where sbt dependency resolution did not work, so manually downloading jar-files was a necessity for me.


3 comments:

  1. I wonder how did you include github contents inside your blog? Can you tell me how to do it? Thanks

    ReplyDelete
  2. Where is the actual code for this?

    ReplyDelete
  3. Has the linked code from github disappeared?

    ReplyDelete