Introduction To Spray with Scala & AKKA Framework


Spray is an Open-Source toolkit for building RESTful Services on top of Scala & Akka Framework.

Being asynchronous, actor-based, fast, lightweight, modular and testable it’s a great way to connect your Scala applications to the world.

Including library file of spary to scala project:

In your scala project open build.sbt and add below lines

lazy val akkaVersion = “2.4.0”
resolvers += “Sonatype Snapshots” at “”
resolvers ++= Seq(
“Spray Repository” at “”,
“Apache Staging” at “”,
“Scalaz Bintray Repo” at “”

libraryDependencies ++= {
val akkaVersion = “2.3.10”
val sprayVersion = “1.3.3”
“com.typesafe.akka” %% “akka-actor” % akkaVersion,
“io.spray” %% “spray-can” % sprayVersion,
“io.spray” %% “spray-routing” % sprayVersion,
“io.spray” %% “spray-json” % “1.3.1”,
“io.spray” %% “spray-httpx” % sprayVersion,
“io.spray” %% “spray-testkit” % sprayVersion % “test”,
“org.specs2” %% “specs2-core” % “3.6” % “test”,
“com.typesafe.akka” %% “akka-testkit” % akkaVersion % “test”


The above lines of code is to include spray library to your build.sbt. Here Akka 2.3.10 and spray 1.3.3 is used. Please change the version if needed.

Create HTTP Actor

Create Http actor to handle all the http request. In spray all the incoming request is handled by one Akka actor and then the work is distributed to multiple actor.

Create a scala class and name it as HttpServiceActor and extends HttpService with Actor, like below

class HttpServiceActor(connection: DefaultDB) extends HttpService with Actor

After this you should override two methods

implicit def actorRefFactory = context

def receive = runRoute(sample)

Here runRoute is a function in HttpService class. Should pass the path reference variable. Here sample variable is defined as

val sample= path(“sampleTest”) {
get {

“Hello World”


Here ends the implementation of HttpServiceActor. Now it’s time to implement the main part, where we will define the interface, port to which spray will listen.

Create a scala object and name it as ScalaSpray.scala and then extends with App

object ScalaSpray extends App

And define the main method

implicit val system = ActorSystem(“scalaspray”)

val httpServiceActor = system.actorOf(Props(new HttpServiceActor(connection)), “http-service”)

implicit val timeout = Timeout(5.seconds)

IO(Http) ? Http.Bind(httpServiceActor, interface = “localhost”, port = 8080)


Now run the Scala Project. Then open your browser and enter below url


Now you should see Hello World.

I’ll write the next tutorial in some time.

Thank you:)

Leave a Reply

Your email address will not be published. Required fields are marked *