Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get payload from a POST in Play 2.0

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.

like image 485
jglatre Avatar asked Dec 23 '11 19:12

jglatre


3 Answers

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)
like image 149
opensas Avatar answered Nov 16 '22 01:11

opensas


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"))
}
like image 36
chiappone Avatar answered Nov 16 '22 02:11

chiappone


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.

like image 24
ed. Avatar answered Nov 16 '22 01:11

ed.