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
Akka HTTP is a powerful tool for building HTTP applications in Scala. Its actor-based model and seamless integration with other Akka modules make it a great choice for creating scalable and efficient web services. By following this guide, you should have a basic understanding of how to set up and run a simple Akka HTTP server. Refer above link to explore the documentation and experiment with more features to build more complex applications. For other blogs refer this link.
Happy coding with Akka HTTP and Scala!……….. Click Here to Get Sample Code.