Incerteza
Incerteza

Reputation: 34884

Get POST parameters and headers

I have a RESTFul API service and I want to get the parameters (and headers) in a POST request. There is no information about it at http://www.playframework.com/documentation/2.1.x/ScalaRouting

By saying, I have RESTFul API service, I mean that there is no view page in it.

How do I do that?

Upvotes: 0

Views: 145

Answers (2)

pedrofurla
pedrofurla

Reputation: 12783

That's because what you want is in Actions.

// param is provided by the routes.
def myApiCall(param:String) = Action { request =>
  // do what you want with param
  // there are some of the methods of request:
  request.headers
  request.queryString
  Ok("") // probably there is an Ok with a better representation of empty. But it will give you a status 200 anyways...
}

More about Request

Or if you just want param:

def myApiCall(param:String) = Action {
  //stuff with param
  Ok("...")
}

For both cases the route would look like:

POST /myapicall/:param WhateverClass.myApiCall(param)
  • Notice: renamed myApiClass to myApiCall, it was the original intention.

Upvotes: 2

Jatin
Jatin

Reputation: 31724

Here is a small example:

In routes:

GET        /user/:name     controllers.Application.getUserInfo(name)

In Application.scala

object Application extends Controller {

import play.api.libs.json._
import scala.reflect.runtime.universe._

/**
   * Generates a Json String of the parameters.
   * For example doing getJson(("status" -> "success")) returns you a Json String:
   * """
   * {
   *   "status" : "success"
   * }
   */
def getJson[T: Writes](pairs: (String, T)*): String = {
    val i = pairs.map { case (x, y) => (x -> (y: Json.JsValueWrapper)) }
    Json.obj(i: _*).toString
  }

def getUserInfo(name:String) = Action{ implicit request =>
    val user = //get User object of name
    Ok(getJson(("firstName" -> user.firstName),("lastName" -> user.lastName)))
}
//Directly calling Json.obj(("firstName" -> user.firstName),("lastName" -> user.lastName)).toString() will also do.  getJson is used to make it more readable.

Upvotes: 1

Related Questions