0

我有一个 RESTFul API 服务,我想在 POST 请求中获取参数(和标头)。http://www.playframework.com/documentation/2.1.x/ScalaRouting上没有关于它的信息

说,我有 RESTFul API 服务,我的意思是里面没有视图页面。

我怎么做?

4

2 回答 2

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...
}

更多关于请求

或者,如果您只想要参数:

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

对于这两种情况,路线如下所示:

POST /myapicall/:param WhateverClass.myApiCall(param)
  • 注意:将 myApiClass 重命名为 myApiCall,这是本意。
于 2013-10-08T04:43:38.347 回答
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.
于 2013-10-08T08:11:35.393 回答