TheCrystalShip
TheCrystalShip

Reputation: 259

Scala akka http server - print POST messages

I have a simple scala server that listens on localhost:9000, and I want to print the body of each post message I get.

When I send a post message to localhost:9000 I get the "Hello, World!". I want to print the actual data that was sent in the POST body message.

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

object Main extends App {
  val host = "0.0.0.0"
  val port = 9000
  implicit val system: ActorSystem = ActorSystem("helloworld")
  implicit val materializer: ActorMaterializer = ActorMaterializer()
  def route = path("hello") {
    post {
      println("we got a post message!")
      complete("Hello, World!")
    }
  }
  Http().bindAndHandle(route, host, port)
}

Any help would be appreciated.

Upvotes: 1

Views: 930

Answers (2)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

One way is to extract request with directive extractRequest, convert the entity to Strict. And map and onComplete to the Future

def route = path("hello") {
  post {
    extractRequest {req =>
      req.entity.toStrict(2.seconds).map(_.data.utf8String).onComplete(println)
      complete("Hello, World!")
    }
  }
}

Upvotes: 1

ulubeyn
ulubeyn

Reputation: 3021

All you need to do is just extracting data from post request. For example;

...
def route = path("hello") {
     post {
          entity(as[String]) { str =>
               println(str)
               ... // do stg
          }
     }
}
...

You can take a look at this page. I hope it helps!

Upvotes: 1

Related Questions