Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request using play ws in Scala

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.

like image 807
winu_ram Avatar asked Jul 03 '17 14:07

winu_ram


2 Answers

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

like image 189
Tarun Bansal Avatar answered Oct 11 '22 20:10

Tarun Bansal


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.

like image 29
ppeg34 Avatar answered Oct 11 '22 18:10

ppeg34