8

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 2

11

You need to import BodyWritables for json objects, Add following import statements to your source file

import play.api.libs.ws.JsonBodyReadables._
import play.api.libs.ws.JsonBodyWritables._

For more information have a look at official documentation

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Has the documentation around this been updated yet? I can't use intelli sense when adding "asScala" to see what functions are available and even adding a header is now difficult
I found that adding .asInstanceOf[AhcWSClient] between the .asScala() and url() helps with the intelli sense at least.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.