我有一个RESTFul API服务,我想在POST请求中获取参数(和标题)。 http://www.playframework.com/documentation/2.1.x/ScalaRouting
没有相关信息通过说,我有RESTFul API服务,我的意思是它没有查看页面。
我该怎么做?
答案 0 :(得分:2)
那是因为你想要的是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...
}
有关Request
的更多信息或者如果你只想要参数:
def myApiCall(param:String) = Action {
//stuff with param
Ok("...")
}
对于这两种情况,路线看起来像:
POST /myapicall/:param WhateverClass.myApiCall(param)
答案 1 :(得分:1)
这是一个小例子:
在路线中:
GET /user/:name controllers.Application.getUserInfo(name)
在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.