Graffiti Rules: Hello World in Spray

Today we are going to get started with a tool to develop REST API: Spray. In order to create those APIs, Spray defines a DSL (Domain Specific Language) to define the routes and responses to the HTTP requests we receive. There are other options to create this type of APIs such as scalatra, Play, Lift… However, Spray serves us well as we will later speak about its successor: Akka-HTTP. But not so fast, let’s go bit by bit.

computers20graffiti20error20technology20explorer201440x90020wallpaper_www-wallpaperfo-com_98

The aim of this post is to make an introductory incursion. We can count ourselves lucky if we come to implement a Hello World with Spray by the end of it. To do that, it is required to know which are the modules with which the framework is built. These are some of main ones:
  • spray-can: HTTP server that will allow us to run our API.
  • spray-routing: DSL to describe the routes used to define the desired behaviour. Unlike other frameworks (such as Play), the routes are defined by code, instead of using a text file or a configuration file.
  • spray-http: module in charge of modelling and managing the HTTP protocol.
  • spray-json: module used for the serialization and deserialization of messages in JSON format. It can be replaced with other JSON serialization modules such as play-json, jackson…
  • spray-testkit: small DSL to test the endpoints in a really simple way.

This first example, due to its simplicity, won’t need all of them. We’ll be using the rest of them further on. So, the first thing we need to do is to build our SBT file with the needed dependencies. In our case, we will only be using spray-can,spray-routing and akka. Thus, we add those dependencies to the build.sbt file:

val akkaV = "2.3.9"
val sprayV = "1.3.3"

libraryDependencies ++= Seq(
    "io.spray" %% "spray-can" % sprayV,
    "io.spray" %% "spray-routing" % sprayV,
    "com.typesafe.akka" %% "akka-actor" % akkaV
  )

Once the configuration is ready, we shall start writing the Scala code. It is important to know that Spray is built on top of Akka. As we’ll see, much of its functionality is based on its use of actors.

First, we define our route. In such a route we will simply mark that we a GET is received, a Hello World will be sent as response:

import spray.routing._
trait ApiRoute extends HttpService {

 val myApiRoute =
   get {
     complete("Hello World!")
   }
}

As can be appreciated, a mixin with HttpService is required. Furthermore, if a response needs to be returned, it is also mandatory for it to be encapsulated in a complete method. The part of spray-routing that we’re using here is the get directive, which defines the behaviour towards GET requests (quite logical, as it should).

Now, we have to define an actor that uses that route. This is really simple as it is completely based in Akka. The only rare (or new) thing is that we’ll have to define its behaviour with a method called runRoute, which requires a route. And which route is this? Well, naturally, it’ll be the one we’ve just defined in the ApiRoute trait:

import akka.actor.Actor
import spray.routing._

class ApiActor extends Actor with ApiRoute {

  def actorRefFactory = context

  def receive = runRoute(myApiRoute)
}

Now, all that remains is to run the API and bind it to a port. For this, the first thing we need to do is to create an ActorSystem. Once it is created, we create an actor of the type ApiActor (the actor we’ve just defined in the previous paragraph). Finally, we send a Bind message to it with the IP and port to which it should be binded:

import akka.actor.{ ActorSystem, Props }
import akka.io.IO
import akka.util.Timeout
import akka.pattern.ask

import spray.can.Http

import scala.concurrent.duration._

object Main extends App {

  implicit val system = ActorSystem("My-System")
  val apiActor = system.actorOf(Props[ApiActor])

  implicit val timeout = Timeout(3 seconds)

  IO(Http) ? Http.Bind(apiActor, interface = "localhost", port = 8080)

}

And this is it. Now, we just have to execute the application, open our favourite browser and go to localhost:8080 to see a wonderful yet surprising ‘HELLO WORLD!’ 🙂

tumblr_mamiy1kp641qcp26yo1_400

Anuncios

One thought on “Graffiti Rules: Hello World in Spray

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s