Codementor Events

How to create an Akka HTTP Server

Published Sep 28, 2017Last updated Mar 26, 2018
How to create an Akka HTTP Server

The Akka HTTP modules implement a full server-side and client-side HTTP stack on top of akka-actor and akka-stream. It offers two different API with different levels of abstraction: a high-level one and a low-level one.

The high-level routing API of Akka HTTP provides a DSL to describe HTTP “routes” and how they should be handled. Each route is composed of one or more levels of Directive s that narrows down to handling one specific type of request.

The low-level Akka HTTP server API allows for handling connections or individual requests by accepting HttpRequestobjects and answering them by producing HttpResponse objects.

Adding the Akka-HTTP dependency

Akka HTTP is provided in a separate JAR file, to use it we should include the following dependency in your build.sbt file

"com.typesafe.akka" %% "akka-http" % "10.0.9"

Creating Server basic structure

First we add an Scala file to our project and create an object that extends from App and Directives.

import akka.http.scaladsl.server.Directives 

object Server extends App with Directives {}

Then we need to add the ActorSystem and ActorMaterializer to that object.

import akka.http.scaladsl.server._ 
import akka.actor.ActorSystem 
import akka.stream.ActorMaterializer 

object Server extends App with Directives { 
  implicit val system = ActorSystem("actor-system") 
  implicit val materializer: ActorMaterializer = ActorMaterializer() 
}

Now we can get the server up by adding the following lines after the implicits.

val routes: Route = 
  path("/test") { 
    complete("test") 
  }
  
Http().bindAndHandle(routes, "0.0.0.0", 8002)

The first lines define an example route /test which returns the text: test while the last one allows us to bind an IP and port to a set of routes.

Server basic Structure:

import akka.http.scaladsl.server._ 
import akka.actor.ActorSystem 
import akka.stream.ActorMaterializer 

object Server extends App with Directives { 
  implicit val system = ActorSystem("actor-system") 
  implicit val materializer: ActorMaterializer = ActorMaterializer() 
  
  val routes: Route = 
    path("/test") { 
      complete("test") 
    } 
    
  Http().bindAndHandle(routes, "0.0.0.0", 8002) 
}

Defining Routes

Now we are going to replace the example route /test with some more interesting ones.

All the routes we are going to define in our server are implemented using Akka-HTTP directives and have to be assigned to a Route type variable. This variable is the one which will be used as the first parameter of thebindAndHandle method.

The most easy way to add a new route is using the directive ‘path‘ along with a path as we saw in the example route above.

All the directives should finish with a complete method call.

val routes: Route = 
  path("test") { 
    complete("test") 
  }

Inside the path we can use different directives depending on the HTTP method that we want to use. Here is an example using the POST verb.

val routes: Route = 
  path("test") { 
    post { 
      complete("test") 
    } 
  }

If we want to add a new route we can concatenate two path directives just using the ~ symbol.

val routes: Route = 
  path("test") { 
    ... 
  } ~ 
  path("test2") { 
    ... 
  }

Responding requests

Till now we saw how to return a text for an endpoint using the complete method and a text. But what about if we want to return JSON data? Well certainly we can do something like this:

val routes: Route = 
  path("test") { 
    post { 
      complete("{\"my_key\":\"my_value\"}") 
    } 
  }

However this JSON will be returned with a wrong content type.

In order to set the right content type we have to use the Akka HTTP low level objects HttpResponse and ResponseEntity

val routes: Route = 
  path("test") { 
    post { 
      val resp: ResponseEntity = HttpEntity(ContentTypes.`application/json`,"{\"my_key\":\"my_value\"}") 
      complete(HttpResponse(StatusCodes.OK, entity = resp) 
    } 
  }

Note: Besides HttpResponse object has a parameter to define headers the Content Type can not be defined in that parameter. It has to be defined in the HttpEntity.

Dealing with input data in URLs

If we want to get a number from an URL we should use the IntNumber object.

val routes: Route = 
  path("test" / IntNumber) { id => 
    get { 
      complete(s"get test - $id") 
    }
  }

But if we want to get the content from one / to the next one (or the url end if there is no one more) we should use the Segment object.

val routes: Route = 
  path("test" / Segment ) { data => 
    get { 
      complete(s"get test - $data") 
    } 
  }

Of course there is more options but IntNumber and Segment are the two more useful ones.

We can also combine more than one input data in the same route as follows:

val routes: Route = 
  path("test" / Segment / IntNumber) { (data, id) => 
    get { 
      complete(s"get test - $data, $id") 
    } 
  }

Dealing with input data in request body

One common thing when we work with HTTP requests is to get information from the request body. This information has to be converted into an Scala data type in order to be able to work with it in our Akka HTTP Server.  To do that we could use the entity(as(..)) structure.

Example:

val routes: Route = 
  path("test") { 
    post { 
      entity(as[String]) { param => 
        ... 
      } 
    } 
  }

In this example param contains the request body as an String.

This can be accomplished due Akka HTTP includes marshallers for some basic data types. Default marshallers are provided for simple objects like String or ByteString.

Dealing with JSON

Most of the times the request body information comes as a JSON structure and deal with that it’s a little more complex. There is no default marshaller for your own JSON data of course, so you have to define it.

There are some JSON libraries which can help but the most common library for these cases is the spay-json library. And here we are going to use this library to define our own marshaller.

First of all we have to define a case class with all the parameters that we are going to receive in the request JSON body.

So, for example, if our JSON data is something like:

{ names: ['jhon', 'freddy', 'kurt'], id: 10 }

We should define a case class like this:

case class TestAPIParams(names: List[String], id: Int)

But after defining the right case class we have to define the marshaller.

To do that, we have to define a trait extending from sprayJsonSupport and DefaultJsonProtocol. Inside this trait we have to define and implicit using jsonFormatX where X is the amount of parameters we have. In our case we should define the trait as follows:

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val testAPIJsonFormat = jsonFormat2(TestAPIParams)
}

Once we have a marshaller for our JSON data we have to extend the object in which we are defining the route.

object Server extends App with Directives with JsonSupport { ... }

And now we can use the entity(as(...)) structure with the our case class

path("test") { 
  post { 
    entity(as[TestAPIParams]) { params => 
      ... // We can use params.names and params.id 
    }
  }
}

Final comments

It may seem a little difficult to develop a server over Akka HTTP from scratch and certainly there are complex things in the library. However following these steps it’s easy to start and have the basic server structure and functionality quite soon.  Then it’s only hard work and read the documentation. Luckily Akka HTTP has a very complete and clear official documentation, fully of examples.

This blog post was originally posted in Scalents

Discover and read more posts from Andres Daniel Gazzoli
get started
post commentsBe the first to share your opinion
Show more replies