I'm trying to implement a REST API with Play 2.0 (Scala) but I'm getting stuck in POST method. How do I get the payload from Request object? I haven't find any documentation about it and have been unable to figure out from source code.
have a look at this article on playlatam
also check this question on google list
for java (with a param names java_name):
String name = request().body().asFormUrlEncoded().get("java_name")[0];
for scala (with a param names scala_name):
def name = request.body.asFormUrlEncoded.get("scala_name")(0)
You should be able to do the following:
def index = Action { request =>
val body = request.body
}
And also things like:
def index = Action { request =>
val name = request.queryString.get("name").flatMap(_.headOption)
Ok("Hello " + name.getOrElse("Guest"))
}
I had to do it somewhat differently (maybe I'm on a newer version of the codebase):
my javascript:
$(document).ready(function(){
$.post( "/ping", {one: "one", two: "two" },
function( data ){
console.log(data); //returns {"one":"one","two":"two"}
})
});
my route:
POST /ping controllers.Application.ping()
My controller method:
def ping() = Action{ request =>
val map : Map[String,Seq[String]] = request.body.asFormUrlEncoded.getOrElse(Map())
val one : Seq[String] = map.getOrElse("one", List[String]())
val two : Seq[String] = map.getOrElse("two", List[String]())
Ok(
toJson( JsObject(List( "one"->JsString(one.first), "two"->JsString(two.first))))
)
}
I assume this will change in the final version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With