Playframework(17)RESTful and Scala

Playframework(17)RESTful and Scala

I installed the latest activator-1.3.5 from link from here https://downloads.typesafe.com/typesafe-activator/1.3.5/typesafe-activator-1.3.5.zip.

Then I create the project
> activator new sillycat-scalarest simple-rest-scala

Start the project
> activator run

Run the test
> activator test

And all the SBT command should be working as well.

Run this on a port number
> sbt -Dhttp.port=8000 run

The sample project is  sillycat-scalarest

Some important Codes are as follow:
conf/routes
GET      /api/v1/book                     controllers.BookController.listBooks
POST     /api/v1/book                     controllers.BookController.saveBook
GET      /api/v1/book/:id                 controllers.BookController.getBook(id:String)
PUT      /api/v1/book/:id                 controllers.BookController.updateBook(id:String)
DELETE   /api/v1/book/:id                 controllers.BookController.deleteBook(id:String)

app/controllers/BookController
package controllers

import play.api.libs.json._
import play.api.mvc._
import models.Book

object BookController extends Controller {

  def listBooks = Action {
    Ok(Json.toJson(Book.books))
  }

  def saveBook = Action(BodyParsers.parse.json) { request =>
    val b = 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"))
      }
    )
  }

  def getBook(id:String) = Action {
    Book.getBook(id) match {
      case Some(b) => Ok(Json.toJson(b))
      case _ => Ok(Json.obj("status" -> "OK", "message" -> "Book Not Found!"))
    }
  }

  def deleteBook(id:String) = Action {
    Book.deleteBook(id)
    Ok(Json.obj("status" -> "OK"))
  }

  def updateBook(id:String) = Action(BodyParsers.parse.json){ request =>
    val b = 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
package models

import play.api.libs.json.Json

case class Book(var id:Option[String], title: String, author: String, isbn: String)

object Book {

  implicit val bookWrites = Json.writes[Book]
  implicit val bookReads = Json.reads[Book]

  var books = List(
    Book(Some("1"),"Python in Action", "Xman", "isbn-001"),
    Book(Some("2"), "R in Action", "Hero", "isbn-002")
  )

  def addBook(b: Book) = {
    val r = scala.util.Random
    b.id = Some(r.nextInt(10000000).toString)
    books = books ::: List(b)
  }

  def getBook(id:String):Option[Book] = {
    val finds = books filter { book =>
      book.id.get.equals(id)
    }
    finds.size match {
      case 1 => Some(finds(0))
      case _ => None
    }
  }

  def deleteBook(id:String) = {
    val filters = books filterNot { book =>
      book.id.get.equals(id)
    }
    books = filters
  }

  def updateBook(b:Book) = {
    val filters = books filterNot { book =>
      book.id.get.equals(b.id.get)
    }
    books = filters ::: List(b)
  }
}

There is some other things we need to pay attention to, logging, testing, validation and etc. And the persist layer is just a mock.

References:
http://sillycat.iteye.com/blog/2199668
http://sillycat.iteye.com/blog/2192224

Playframework
http://sillycat.iteye.com/blog/1743396 old installation
http://sillycat.iteye.com/blog/1753450 scala http programming

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

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

猜你喜欢

转载自sillycat.iteye.com/blog/2241901