Ryan Medlin
Ryan Medlin

Reputation: 189

How to get all request parameters in Play and Scala

 case GET(Path("/rtb_v1/bidrequest")) => Action {  implicit request =>

I want to take the request object above and get all of the key/value pairs sent in the form post and flatten it into a Map[String,String]

i have gone through all the documents and am at a dead end.

This is pretty freaking easy in Java/Servlets I;m wondering why there is no documentation on a simple thing like this anywhere..

Map<String, String[]> parameters = request.getParameterMap();

Upvotes: 13

Views: 22890

Answers (4)

Louis Querel
Louis Querel

Reputation: 608

You might have to use the following:

request.queryString.map { case (k,v) => k -> v.mkString }).toSeq: _*

Upvotes: 0

cchantep
cchantep

Reputation: 9168

It won't work if request is using POST method. Following code can be used:

req.body match {
  case AnyContentAsFormUrlEncoded(params) ⇒
    println(s"urlEncoded = $params")
  case mp @ AnyContentAsMultipartFormData(_) ⇒
    println(s"multipart = ${mp.asFormUrlEncoded}")
}

Upvotes: 1

Ivan Meredith
Ivan Meredith

Reputation: 2222

As an alternative to the way that Kim does it, I personally use a function like..

def param(field: String): Option[String] = 
  request.queryString.get(field).flatMap(_.headOption)

Upvotes: 9

Kim Stebel
Kim Stebel

Reputation: 42047

Play's equivalent of request.getParamterMap is request.queryString, which returns a Map[String, Seq[String]]. You can flatten it to a Map[String, String] with

request.queryString.map { case (k,v) => k -> v.mkString }

And here is the documentation.

Upvotes: 27

Related Questions