import net.liftweb.http._
import net.liftweb.http.rest._
object MyRest extends RestHelper {
}
LiftRules.dispatch.append(MyRest) // stateful — associated with a servlet container session LiftRules.statelessDispatchTable.append(MyRest) // stateless — no session created
serve {
case Req("api" :: "static" :: _, "xml", GetRequest) => <b>Static</b>
case Req("api" :: "static" :: _, "json", GetRequest) => JString("Static")
}
serve {
case XmlGet("api" :: "static" :: _, _) => <b>Static</b>
case JsonGet("api" :: "static" :: _, _) => JString("Static")
}
serve {
case "api" :: "static" :: _ XmlGet _=> <b>Static</b>
case "api" :: "static" :: _ JsonGet _ => JString("Static")
}
serve {
case "api" :: "user" :: id :: _ XmlGet _ => <b>ID: {id}</b>
case "api" :: "user" :: id :: _ JsonGet _ => JString(id)
}
serve {
case "api" :: "user" :: AsLong(id) :: _ XmlGet _ => <b>ID: {id}</b>
case "api" :: "user" :: AsLong(id) :: _ JsonGet _ => JInt(id)
}
serve {
case "api" :: "user" :: _ XmlPut xml -> _ => // xml is a scala.xml.Node
User.createFromXml(xml).map { u => u.save; u.toXml}
case "api" :: "user" :: _ JsonPut json -> _ => // json is a net.liftweb.json.JsonAST.JValue
User.createFromJson(json).map { u => u.save; u.toJson}
}
trait Convertable {
def toXml: Elem
def toJson: JValue
}
serveJx {
case Get("api" :: "info" :: Info(info) :: _, _) => Full(info)
}
// extract the parameters, create a user
// return the appropriate response
def addUser(): Box[UserInfo] =
for {
firstname <- S.param("firstname") ?~ "firstname parameter missing" ~> 400
lastname <- S.param("lastname") ?~ "lastname parameter missing"
email <- S.param("email") ?~ "email parameter missing"
} yield {
val u = User.create.firstName(firstname).
lastName(lastname).email(email)
S.param("password") foreach u.password.set
u.saveMe
}
serveJx {
case Post("api" :: "add_user" :: _, _) => addUser()
}
(C) 2012 David Pollak