Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Akka Http

Akka HTTP is a suite of libraries for building and consuming HTTP-based services in Scala and Java. It's part of the Akka project, which provides tools for building concurrent, distributed, and resilient message-driven applications. Akka HTTP is designed around the actor model and asynchronous, non-blocking I/O operations, making it ideal for high-performance applications that need to handle many concurrent connections. Here’s a simple tutorial to get you started with Akka HTTP in Scala.

Setting Up the Project

First, make sure you have sbt (Scala Build Tool) installed. Create a new sbt project and add the following dependencies to your build.sbt file to include Akka HTTP and Akka Streams:

name := "akka-http-tutorial"

version := "0.1"

scalaVersion := "2.13.6"

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-http" % "10.2.4",
  "com.typesafe.akka" %% "akka-actor-typed" % "2.6.14",
  "com.typesafe.akka" %% "akka-stream" % "2.6.14"
)

Creating a Simple HTTP Server

Next, let’s create a simple HTTP server that responds with "Hello, Akka HTTP!" when accessed. Create a Scala object in src/main/scala named WebServer.scala:

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import scala.io.StdIn

object WebServer {
  def main(args: Array[String]): Unit = {

    implicit val system = ActorSystem("mySystem")
    import system.dispatcher // needed for the future flatMap/onComplete in the end

    val route =
      pathEndOrSingleSlash { // matches the root path
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Hello, Akka HTTP!</h1>"))
      }

    val bindingFuture = Http().newServerAt("localhost", 8080).bind(route)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }
}

This code does the following:

  • Initializes an ActorSystem, which is a heavyweight structure that will govern the lifecycle of our application.
  • Defines a simple route that matches the root URL path and responds with an HTML greeting.
  • Starts an HTTP server on localhost port 8080, binding it to the defined route.
  • Waits for the user to press RETURN before shutting down the server.

Running Your Server

To run your server, use sbt to compile and execute your application:

sbt run

Navigate to http://localhost:8080 in your web browser, and you should see the greeting "Hello, Akka HTTP!" displayed.

Expanding Your Application

Akka HTTP is not limited to simple text responses. You can serve JSON, handle form submissions, manage websockets, and much more. For a slightly more complex example, let's modify the route to handle different paths and HTTP methods:

val route =
  concat(
    pathEndOrSingleSlash {
      complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Welcome to Akka HTTP!</h1>"))
    },
    path("hello") {
      get {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h2>Hello, GET request!</h2>"))
      } ~
      post {
        complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h2>Hello, POST request!</h2>"))
      }
    }
  )

This expanded route now also matches the /hello path and distinguishes between GET and POST requests, providing different responses for each.