Say Hello to “Akka-Http”


Hello folks, Hope you are enjoying your coding days!!! in this blog, I will explain a cool technology named Akka-Http which i have recently explored in my coding days!!

Introduction

The Akka HTTP implements a full server- and client-side HTTP stack on top of akka-actor and akka-stream. It’s not a web-framework but rather a more general toolkit for providing and consuming HTTP-based services.

Akka.Http comes with server side and client side libraries. It also comes with good support for standard serialization such as JSON/XML and the ability to roll your own serialization if you want to.

It also comes with a fairly nifty routing DSL which is very much inspired by the work done in Spray(Spray is an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka.)

Adding Akka-Http dependency in your project

To start using akka-http, you should add the following dependency to project. I am using sbt for build management. You can also use other build tools like maven.

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

Mind that Akka HTTP comes in two modules: akka-http and akka-http-core.

Because akka-http depends on akka-http-core you don’t need to bring the latter explicitly. Still you may need to this in case you rely solely on the low-level API(make sure the Scala version is a recent release of version 2.11 or 2.12.)

new-build

Hosting The Service

To have  a correctly formed/hostable server side we need a couple of things in place, namely the following

  • An actor system
  • A materializer (Akka http uses flows which is the subject of the next and final post)
  • An execution context
  • Routing

Once we have these things it is really just a question of binding the route to a host name and port.

1. Create Actor System

Akka HTTP uses akka actors for handling concurrent requests. So in the first line we have to create akka actor system.

  implicit val system = ActorSystem("my-system")

2. Create ActorFlowMaterilizer

Akka HTTP uses akka reactive streams for stream processing on TPC. So in a reactive system,we need to specify flow materializer which specifies the how requests/repose flow get processed. In akka-http, actors will be used for handling request and response flows. So we use ActorMaterializer here.

ActorMaterializer is responsible for creating actors that will eventually run the processing flow and it requires ActorSystem to be available implicitly.

implicit val materializer = ActorMaterializer()

3. Defining the route

Route specifies the URI endpoints REST server exposing. It is combination of multiple paths, 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 level of Directive s that narrows down to handling one specific type of request.

There are some common routing DSL bits and bobs, such as:

  • path : which satisfies the route name part of the route
  • get : which tells us that we should go further into the route matching if it’s a GET http request and it matched the path route DSL part
  • post: which tells us that we should go further into the route matching if it’s a POST http request and it matched the path route DSL part
  • complete : This is the final result from the route

Example:-

val route =
  path("hello") {
    get {
      complete(HttpEntity(
    ContentTypes.`text/html(UTF-8)`,
    "Say hello to akka-http"
))
    }
  } ~
  path("randomitem") {
    get {
      // will marshal Item to JSON
      complete(Item("thing", 42))
    }
  } ~
  path("saveitem") {
    post {
      // will unmarshal JSON to Item
      entity(as[Item]) { item =>
        println(s"Server saw Item : $item")
        complete(item)
      }
    }
  }

What Directives Do?

A directive can do one or more of the following:

  • Transform the incoming RequestContext before passing it on to its inner route (i.e. modify the request)
  • Filter the RequestContext according to some logic, i.e. only pass on certain requests and reject others
  • Extract values from the RequestContext and make them available to its inner route as “extractions”
  • Chain some logic into the RouteResult future transformation chain (i.e. modify the response or rejection)
  • Complete the request

4. Bind

Once we have all pieces in place, we need to create a server and bind to this route, address and port.

Http().bindAndHandle(route,"localhost",8383)

This creates and runs a simple http server at http://localhost:8383.

Here is the whole example :-

Screenshot from 2017-06-11 23-11-06

Hope this blog will provide some help and give you brief  introduction to Akka-Http .


knoldus-advt-sticker


Advertisements
This entry was posted in Scala and tagged , , , . Bookmark the permalink.

One Response to Say Hello to “Akka-Http”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s