Playframework(17)RESTful and Scala

Playframework(17)RESTfulandScala

Iinstalledthelatestactivator-1.3.5fromlinkfromherehttps://downloads.typesafe.com/typesafe-activator/1.3.5/typesafe-activator-1.3.5.zip.

ThenIcreatetheproject

>activatornewsillycat-scalarestsimple-rest-scala

Starttheproject

>activatorrun

Runthetest

>activatortest

AndalltheSBTcommandshouldbeworkingaswell.

Runthisonaportnumber

>sbt-Dhttp.port=8000run

Thesampleprojectissillycat-scalarest

SomeimportantCodesareasfollow:

conf/routes

GET/api/v1/bookcontrollers.BookController.listBooks

POST/api/v1/bookcontrollers.BookController.saveBook

GET/api/v1/book/:idcontrollers.BookController.getBook(id:String)

PUT/api/v1/book/:idcontrollers.BookController.updateBook(id:String)

DELETE/api/v1/book/:idcontrollers.BookController.deleteBook(id:String)

app/controllers/BookController

packagecontrollers

importplay.api.libs.json._

importplay.api.mvc._

importmodels.Book

objectBookControllerextendsController{

deflistBooks=Action{

Ok(Json.toJson(Book.books))

}

defsaveBook=Action(BodyParsers.parse.json){request=>

valb=request.body.validate[Book]

b.fold(

errors=>{

BadRequest(Json.obj("status"->"OK","message"->JsError.toFlatJson(errors)))

},

book=>{

Book.addBook(book)

Ok(Json.obj("status"->"OK"))

}

)

}

defgetBook(id:String)=Action{

Book.getBook(id)match{

caseSome(b)=>Ok(Json.toJson(b))

case_=>Ok(Json.obj("status"->"OK","message"->"BookNotFound!"))

}

}

defdeleteBook(id:String)=Action{

Book.deleteBook(id)

Ok(Json.obj("status"->"OK"))

}

defupdateBook(id:String)=Action(BodyParsers.parse.json){request=>

valb=request.body.validate[Book]

b.fold(

errors=>{

BadRequest(Json.obj("status"->"OK","message"->JsError.toFlatJson(errors)))

},

book=>{

book.id=Some(id)

Book.updateBook(book)

Ok(Json.obj("status"->"OK"))

}

)

}

}

app/models/Book.scala

packagemodels

importplay.api.libs.json.Json

caseclassBook(varid:Option[String],title:String,author:String,isbn:String)

objectBook{

implicitvalbookWrites=Json.writes[Book]

implicitvalbookReads=Json.reads[Book]

varbooks=List(

Book(Some("1"),"PythoninAction","Xman","isbn-001"),

Book(Some("2"),"RinAction","Hero","isbn-002")

)

defaddBook(b:Book)={

valr=scala.util.Random

b.id=Some(r.nextInt(10000000).toString)

books=books:::List(b)

}

defgetBook(id:String):Option[Book]={

valfinds=booksfilter{book=>

book.id.get.equals(id)

}

finds.sizematch{

case1=>Some(finds(0))

case_=>None

}

}

defdeleteBook(id:String)={

valfilters=booksfilterNot{book=>

book.id.get.equals(id)

}

books=filters

}

defupdateBook(b:Book)={

valfilters=booksfilterNot{book=>

book.id.get.equals(b.id.get)

}

books=filters:::List(b)

}

}

Thereissomeotherthingsweneedtopayattentionto,logging,testing,validationandetc.Andthepersistlayerisjustamock.

References:

Playframework

restscala

http://www.typesafe.com/activator/template/simple-rest-scala

https://github.com/faubertin/scala-play-rest-example

相关推荐