Build your first API with Scala and Akka HTTP

Reading Time: 3 minutes

Akka is a free and open-source toolkit and runtime simplifying the construction of concurrent and distributed applications on the JVM. It is built by Lightbend. Akka supports multiple programming models for concurrency, but it prefers actor-based concurrency. One can integrate this library into any JVM support language. It implements Actor Based Model. The Actor Model provides a higher level of abstraction for writing concurrent and distributed applications. It has several modules that help to build such applications, and Akka HTTP is one of them.

What is Akka HTTP?

It is an Akka-based HTTP library for building RESTful services. It has both client-side and server-side utilities, but we will focus on the server-side in this tutorial. You should be familiar with Scala and you should have SBT and IntelliJ set up and installed on your system. So let’s build a simple API using Scala and Akka HTTP!

Project setup

We’ll be using sbt version 1.5.2 and Scala version 2.12.12. Let’s start by adding the required dependencies. Because Akka HTTP depends on actors and streams. We’ll need to add those libraries as well.

Add the following code in your build.sbt file:

val AkkaVersion = "2.6.8"
val AkkaHttpVersion = "10.2.4"
libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-actor-typed" % AkkaVersion,
  "com.typesafe.akka" %% "akka-stream" % AkkaVersion,
  "com.typesafe.akka" %% "akka-http" % AkkaHttpVersion
)

Let’s create a package under “src/main/scala” name “org.knoldus” and create a scala object named “HttpServer”. Add the following dependencies to create a server with Akka HTTP.

Create Server

Extends the App trait in the Object.

object HttpServer extends App {
}

Now we will need port and host to bind the server. So add the following variable

val host = "localhost"
val port = 7000

Akka HTTP uses akka actors and streams for handling concurrent requests. So we have to add the dependencies for this as well.

 implicit val system = ActorSystem("HTTP_SERVER")
 implicit val materializer : ActorMaterializer.type = ActorMaterializer
 import system.dispatcher

Defining the routes

Route specifies the URI endpoints REST server exposing. Add the following route below the dependencies.

val route =
    pathPrefix("api"){
      get{
        path("hello"){
          complete(StatusCodes.OK, "Hello from Server")
        }
      }
    }

In the above code, we are creating a route with the following properties.

  • “/api/hello” is the directive
  • get is the method
  • complete() will return a Response message as “Hello from Server” with Status code 200

Start the Server

Now we need to create a server and bind to this route, address and port.

val binding = Http().newServerAt(host,port).bindFlow(route)

Now to check if our server is running or not. We will add logging to the console

binding.onComplete{
      case Success(value) =>
        println(s"Server is listening on http://$host:${port}")
      case Failure(exception) =>
        println(s"Failure : $exception")
        system.terminate()
    }

Now we have to run the HttpServer obejct. You can right click and hit Run “HttpServer”.

If the server is running successfully than some message was printed in the console.

Console Logging
Console Logging

Now go to any browser and navigate to http://localhost:7000/api/hello

output
Output on browser

Conclusion

In this post, we have learned how to create a simple server using Akka HTTP and Scala. You can get the complete code here.

References

If you find this article interesting, please check out our other articles.

Written by 

Asbin Bhadra is a Software consultant at Knoldus Inc. Knoldus does niche Reactive and Big Data product development on Scala, Spark, and Functional Java. He is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. His current passions include utilizing the power of Scala, Akka, and Play to make Reactive systems. He has also contributed to various Akka, Play, and Scala-based templates.