Skip to content
Search

Akka:Http:entity

lastmod 2020-08-27created 2020-08-277 edits

Example

package common

final case class Item(name: String, id: Long)

// ...

val route =
  path("hello") {
    get {
      complete(HttpEntity(
    ContentTypes.`text/html(UTF-8)`, 
    "<h1>Say hello to akka-http</h1>"))
    }
  } ~
  path("randomitem") {
    get {
      // will marshal Item to JSON
      complete(Item("thing", 42))
    }
  } ~
  path("saveitem") {
    post {
      // will unmarshal JSON to Item
      entity(as[Item]) { item =>
        println(s"Server saw Item : $item")
        complete(item)
      }
    }
  }

You can see that there are a few common routing DSL bits and bobs in there:

  • path : which satisfies the route name part of the route
  • get : which tells us that we should go further into the route matching if it’s a GET http request and it matched the path route DSL part
  • post: which tells us that we should go further into the route matching if it’s a POST http request and it matched the path route DSL part
  • complete : This is the final result from the route

What Directives Do?

A directive can do one or more of the following.

  • Transform the incoming RequestContext before passing it on to its inner route (i.e. modify the request)
  • Filter the RequestContext according to some logic, i.e. only pass on certain requests and reject others
  • Extract values from the RequestContext and make them available to its inner route as “extractions”
  • Chain some logic into the RouteResult future transformation chain (i.e. modify the response or rejection)
  • Complete the request

See Akka:Http:Directives for details.

See also

Favorite site

author Zer0 sitemap