Server APIs using Akka HTTP

Reading Time: 3 minutes

In this blog, we will be learning to integrate HTTP in our application using Akka HTTP. Basically, we will get to know what Akka HTTP is, what are Low Level and High level server APIs, and how to set HTTPS, etc. So, lets get started.

What is Akka HTTP?

First of all, the Akka HTTP is not a framework, but it is a suite of libraries that is focused on HTTP integration of an application. It is designed for both servers and clients. The Akka HTTP is based on Akka Actor model and Akka Stream.

Low Level Server API:

In the Low Level HTTP Server API, we are actually handling individual requests or connections by a request mechanism called “HttpRequest“, and then sending the response using this “HttpResponse“. It provides a Flow or a Function-level interface, that allows an application to respond to incoming HTTP requests by simply mapping requests to responses.

High Level Server API:

High Level Server API starts from where the Low Level Server API leaves. The Akka HTTP provides a flexible Routing DSL for defining our REST API easily. Here, the concept of Directives and routes come into picture.

Directives:

Directives are basically the building blocks of High Level Http Server API. It specifies what happens and under which condition. There are large number of predefined directives available to use, for instance, get, post, delete, etc. We can also create custom directives and use it.

Routes:

The “Route” is the central concept of Akka HTTP’s Routing DSL. The result of whole directives is called a Route. A Route itself is a function that operates on a RequestContext and returns a RouteResult.

Here is an example code having directives and routes has been defined for a better understanding.

 val simpleRoute : server.Route =
    path("myEndpoint") {
      get {
        complete(StatusCodes.OK)
      } ~
        post {
          complete(StatusCodes.Forbidden)
        }
    }

In the above example code, the get and the post are the directives defined and the whole directive combines to form a route which is named as a simpleRoute.

Methods to Handle Connection Requests:

There are three methods of handling connection requests. They are –

  • Synchronously handling the connection request.

In this case, we capture the request using HttpRequest object and answer the response using HttpResponse object.

    //method 1 --> Synchronously handling the connection request.
    val requestHandler : HttpRequest => HttpResponse = {
        case HttpRequest(HttpMethods.GET, uri, value, entity, protocol) =>
            HttpResponse(
                StatusCodes.OK,
                entity = HttpEntity(
                    ContentTypes.`text/html(UTF-8)`,
                    """
                      |<html>
                      |<body>
                      | Hello from Akka http.
                      |</body>
                      |</html>
                      |""".stripMargin
                )
            )
    }
  • Asynchronously handling the connection request.

In asynchronously handling connection request, we answer the request using Futures in scala.

    val asyncrequestHandler : HttpRequest => Future[HttpResponse] = {
        case HttpRequest(HttpMethods.GET, Uri.Path("/home"), value, entity, protocol) =>
            Future(HttpResponse(
                StatusCodes.OK,
                entity = HttpEntity(
                    ContentTypes.`text/html(UTF-8)`,
                    """
                      |<html>
                      |<body>
                      | Hello from Akka http.
                      |</body>
                      |</html>
                      |""".stripMargin
                )
            )
            )
    }
  • Handling the connection request using Akka Stream Flow.

In this case of connection request handler, we create a flow that turns the http flow into a http response, using the concept of Akka Stream.

 val streamBasedRequestHandeler : Flow[HttpRequest, HttpResponse , _] = Flow[HttpRequest].map {
        case HttpRequest(HttpMethods.GET, Uri.Path("/home"), value, entity, protocol) =>
            HttpResponse(
                StatusCodes.OK,
                entity = HttpEntity(
                    ContentTypes.`text/html(UTF-8)`,
                    """
                      |<html>
                      |<body>
                      | Hello from Akka http.
                      |</body>
                      |</html>
                      |""".stripMargin
                )

            )
    }

Conclusion

Hence, this was all about the basics of Akka Http where we learnt about the Akka Http, the Low and the High Level Server API, concept of Routing DSL and different methods of handling connection requests. Hope you found this blog useful and it added value to your existing knowledge.

References

Low Level Server API
Routing DSL in Akka Http

Written by 

Utkarsh Upadhyay is a Software Consultant at Knoldus Software LLP, having experience of more than 2 years. He has done B. Tech from IMS Engineering College, Ghaziabad. He has a decent knowledge of Scala, Lagom, Kafka, Cassandra, Akka, and Akka Stream. He loves playing and watching cricket and exploring new places.