NashTech Blog

Table of Contents

Introduction

What is Akka HTTP?

Akka HTTP is a library that allows you to build HTTP-based applications using the Akka toolkit. Akka itself is a powerful toolkit for building concurrent, distributed, and fault-tolerant systems using the actor model. It leverages Akka’s actor system to handle HTTP requests in a highly scalable and efficient manner. For more information refer this link.

Why Choose Akka HTTP?

>> Scalability: Handles a large number of connections efficiently.

>> Flexibility: Offers a highly customizable routing DSL.

>> Asynchronous: Built on Akka Streams, making it fully non-blocking.

>> Integration: Works seamlessly with other Akka modules.

Setting Up Your Project

Before we start coding, let’s set up a Scala project with the necessary dependencies. Create a new directory for your project and add a build.sbt file with the following content:

ThisBuild / version := "0.1.0-SNAPSHOT"

ThisBuild / scalaVersion := "2.13.6"

lazy val root = (project in file("."))
  .settings(
    name := "akka-http"
  )

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

Creating a Simple Akka Http Server

Set Up the Main Application

Create a file named SimpleServer.scala in the src/main/scala directory of your project or you can name file as per your need.

package com.nashtech

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

import scala.concurrent.ExecutionContextExecutor

object SimpleServer extends App {
  implicit val system: ActorSystem = ActorSystem("simple-server")
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  implicit val executionContext: ExecutionContextExecutor = system.dispatcher

  // Define the route
  val route: Route =
    path("greet" / Segment) { name =>
      get {
        complete(s"Hello, $name!")
      }
    }

  // Start the server
  val bindingFuture = Http().newServerAt("localhost", 9092).bind(route)
  println("Server online at http://localhost:9092/\nPress RETURN to stop...")
  bindingFuture
    .flatMap(_.unbind()) // Trigger unbinding from the port
    .onComplete(_ => system.terminate()) // Shut down the system
}

Explanation of the Code

Actor System and Materializer: It relies on Akka’s Actor System and Materializer. We need to create these to run our HTTP server.

Route Definition: The route defines how HTTP requests are handled. In this example, we use path as greet/{"name"} to match the root URL and get to handle GET requests. The complete directive sends a “Hello, {message}!” response back to the client.

Starting the Server: The Http().newServerAt("localhost", 9092).bind(route) call starts the server on localhost at port 9092 and binds it to the defined route.

Running the Server

To run the server, open a terminal, navigate to your project directory, and use the following command:

sbt run

You should see output indicating that the server is online. Open your web browser and navigate to http://localhost:9092/. You should see “Hello, {message}!” displayed on the page after hitting this URL -> http://localhost:9092/greet/Manish

Adding more Routes

Let’s expand our server to handle more routes and HTTP methods. Update your SimpleServer.scala file to the following:

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._

val route: Route =
  path("greet" / Segment) { name =>
    get {
      complete(s"Hello, $name!")
    } ~
    post {
      entity(as[String]) { body =>
        complete(s"Received POST request with body: $body")
      }
    }
  } ~
  path("status") {
    get {
      complete(StatusCodes.OK)
    }
  }

Http().newServerAt("localhost", 9092).bind(route)

Conclusion

Picture of Manish Mishra

Manish Mishra

Manish Mishra is a Software Consultant with a focus on Scala, Apache Spark, and Databricks. My proficiency extends to using the Great Expectations tool for ensuring robust data quality. I am passionate about leveraging cutting-edge technologies to solve complex challenges in the dynamic field of data engineering.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top