An Introduction ToAn Introduction To
Rishabh Verma
Software Consultant
Knoldus Software LLP
Agenda
● Why do we need a Http module ?
● Overview Of Akka-Http
● Low level API
● High level API
● Rest Api with Akka-Http(demo)
Need of Http module
● Akka is about building distributed and highly
concurrent applications.
➢ For distribution across threads : (Actors)
➢ For distribution across machines : (Akka clusters)
➢ For distribution across Internet (i.e interaction with
external world) : (Akka-Http)
Overview of Akka-Http
● Toolkit for providing and consuming Http
based services.
● Goal – To interact with external world.
● Implemented on top of Akka Streams, which is
implemented on top of Akka Actors.
● Used for building REST APIs .
Why Akka-http over Spray?
Weaknesses of Spray:
● Spray is no longer being supported
● Handling chunked messages is quite difficult with spray.
● Missing features like Websockets support etc.
Akka-http
● Akka-http is Spray 2.0
● Simplified model structure and fully stream based
Stream
topology
Akka-Http Structure
Akka-http
● Provides high level client and server side APIs.
● Marshalling of custom types Http Entities.
● Unmarshalling custom types Http Entities.
● Provides High level server side API.
● Routing DSL.
● Can handle chunked messages.
● Can receive message headers before the entity.
Marshalling
● "Marshalling" is the process of converting a higher-level
(object) structure into some kind of lower-level
representation.
● Some pre-defined marshallers :
➢ Array[Byte]
➢ String
➢ ByteString
example:
val responseFuture = Marshal(420 ->
errorMsg).to[HttpResponse]
UnMarshalling
● To convert lower level objects into higher level object.
● Some pre-defined unmarshallers :
➢ Byte, Boolean
➢ Short, Int, Long
Client Side API
Server Side API
Low level API
● The low-level Akka HTTP server APIs allows for handling
connections or individual requests by accepting
HttpRequests and answering them by producing
HttpResponses.
● This is provided by the akka-http-core module.
● Lower level API based simply on mapping request to
response.
Low level API (cont..)
val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(
ContentTypes.`text/html(UTF-8)`,
"<html><body>Hello world!</body></html>"))
case HttpRequest(GET, Uri.Path("/ping"), _, _, _) =>
HttpResponse(entity = "PONG!")
case HttpRequest(GET, Uri.Path("/crash"), _, _, _) =>
sys.error("BOOM!")
High Level API
● Low level API becomes uneasy to handle
when we need to create large number to
routes.
● For this we should use higher level API.
● High level API is provided by Akka-http.
High Level API (cont..)
● Directives
● Routing DSL
● Rejection and Exception Handling
● Path matcher
High Level API (cont..)
Directives :
● A "Directive" is a small building block used for creating
routes.
● There are some predefined directives( get, post, complete etc.)
● We can also define our custom directives.
Exmaple: with get and complete directive
val exampleRoute: Route = get {
complete("Received GET")
} ~
High Level API (cont..)
Routing Dsl :
● The "Route" is the central concept of the routing DSL since
all structures you can build with it are instances of a Route.
Ex: type Route = RequestContext => Future[RouteResult].
Path Matcher:
● The path matcher decides to which block the incoming
request will be mapped.
High Level API (cont..)
Rejection :
● ~ operator was introduced, which connects two routes in a
way that allows a second route to get a go at a request if the
first route "rejected" it.
Example:
path("order") { get
{ complete("Received GET")
} ~ post {
complete("Received POST")
}
Http Server
object Server extends App {
implicit val actorSystem = ActorSystem("akka-system")
implicit val flowMaterializer = ActorMaterializer()
val interface = "localhost"
val route: Route = MainService.route
val binding = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server is now online at http:///8080nPress RETURN to stop...")
StdIn.readLine()
binding.flatMap(_.unbind()).onComplete(_ => actorSystem.shutdown()
println("Server is down...")
}
References
● http://doc.akka.io/docs/akka/2.4.8/scala/http/
● https://www.youtube.com/watch?v=y_slPbktLr0
● https://danielasfregola.com/2016/02/07/how-to-build-a-
rest-api-with-akka-http/
An Introduction to Akka http
An Introduction to Akka http

An Introduction to Akka http

  • 1.
    An Introduction ToAnIntroduction To Rishabh Verma Software Consultant Knoldus Software LLP
  • 2.
    Agenda ● Why dowe need a Http module ? ● Overview Of Akka-Http ● Low level API ● High level API ● Rest Api with Akka-Http(demo)
  • 3.
    Need of Httpmodule ● Akka is about building distributed and highly concurrent applications. ➢ For distribution across threads : (Actors) ➢ For distribution across machines : (Akka clusters) ➢ For distribution across Internet (i.e interaction with external world) : (Akka-Http)
  • 4.
    Overview of Akka-Http ●Toolkit for providing and consuming Http based services. ● Goal – To interact with external world. ● Implemented on top of Akka Streams, which is implemented on top of Akka Actors. ● Used for building REST APIs .
  • 5.
    Why Akka-http overSpray? Weaknesses of Spray: ● Spray is no longer being supported ● Handling chunked messages is quite difficult with spray. ● Missing features like Websockets support etc.
  • 6.
    Akka-http ● Akka-http isSpray 2.0 ● Simplified model structure and fully stream based Stream topology
  • 7.
  • 8.
    Akka-http ● Provides highlevel client and server side APIs. ● Marshalling of custom types Http Entities. ● Unmarshalling custom types Http Entities. ● Provides High level server side API. ● Routing DSL. ● Can handle chunked messages. ● Can receive message headers before the entity.
  • 9.
    Marshalling ● "Marshalling" isthe process of converting a higher-level (object) structure into some kind of lower-level representation. ● Some pre-defined marshallers : ➢ Array[Byte] ➢ String ➢ ByteString example: val responseFuture = Marshal(420 -> errorMsg).to[HttpResponse]
  • 10.
    UnMarshalling ● To convertlower level objects into higher level object. ● Some pre-defined unmarshallers : ➢ Byte, Boolean ➢ Short, Int, Long
  • 11.
  • 12.
  • 13.
    Low level API ●The low-level Akka HTTP server APIs allows for handling connections or individual requests by accepting HttpRequests and answering them by producing HttpResponses. ● This is provided by the akka-http-core module. ● Lower level API based simply on mapping request to response.
  • 14.
    Low level API(cont..) val requestHandler: HttpRequest => HttpResponse = { case HttpRequest(GET, Uri.Path("/"), _, _, _) => HttpResponse(entity = HttpEntity( ContentTypes.`text/html(UTF-8)`, "<html><body>Hello world!</body></html>")) case HttpRequest(GET, Uri.Path("/ping"), _, _, _) => HttpResponse(entity = "PONG!") case HttpRequest(GET, Uri.Path("/crash"), _, _, _) => sys.error("BOOM!")
  • 15.
    High Level API ●Low level API becomes uneasy to handle when we need to create large number to routes. ● For this we should use higher level API. ● High level API is provided by Akka-http.
  • 16.
    High Level API(cont..) ● Directives ● Routing DSL ● Rejection and Exception Handling ● Path matcher
  • 17.
    High Level API(cont..) Directives : ● A "Directive" is a small building block used for creating routes. ● There are some predefined directives( get, post, complete etc.) ● We can also define our custom directives. Exmaple: with get and complete directive val exampleRoute: Route = get { complete("Received GET") } ~
  • 18.
    High Level API(cont..) Routing Dsl : ● The "Route" is the central concept of the routing DSL since all structures you can build with it are instances of a Route. Ex: type Route = RequestContext => Future[RouteResult]. Path Matcher: ● The path matcher decides to which block the incoming request will be mapped.
  • 19.
    High Level API(cont..) Rejection : ● ~ operator was introduced, which connects two routes in a way that allows a second route to get a go at a request if the first route "rejected" it. Example: path("order") { get { complete("Received GET") } ~ post { complete("Received POST") }
  • 20.
    Http Server object Serverextends App { implicit val actorSystem = ActorSystem("akka-system") implicit val flowMaterializer = ActorMaterializer() val interface = "localhost" val route: Route = MainService.route val binding = Http().bindAndHandle(route, "localhost", 8080) println(s"Server is now online at http:///8080nPress RETURN to stop...") StdIn.readLine() binding.flatMap(_.unbind()).onComplete(_ => actorSystem.shutdown() println("Server is down...") }
  • 21.