POST request using play ws in Scala

Viewed 5116

I am using play-ws standalone to consume REST service in scala.

val data = Json.obj("message" -> "How are you?")
wsClient.url("http://localhost:5000/token").post(data).map { response =>
      val statusText: String = response.statusText
      println(response.body)
    }

When i run this, i get the following error,

Cannot find an instance of play.api.libs.json.JsObject to WSBody. Define a BodyWritable[play.api.libs.json.JsObject] or extend play.api.libs.ws.ahc.DefaultBodyWritables
    wsClient.url("http://localhost:5000/token").post(data).map { response =>

It tells to define a bodywritable. I have read the documentation but cud't get the "BodyWritable". I am new to scala. Anybody help me please. Thanks in advance.

2 Answers

The current accepted answer does not work in Scala Play 2.7.x (possibly some earlier versions as well).

I couldn't find it in the docs, but you need to explicitly call asScala on the ws object. For example:

  val data = Json.obj("message" -> "How are you?")
  ws
    .asScala()
    .url("http://someurl.com")
    .post(data)
    .map(response => {
      //do something with response
    })

Note: this also returns a scala future instead of a java completion stage.

Related