初めてPlay Scalaを触ってみたが暗中模索も良い所。
APIサーバを建てられるようになることを目標としてとりあえずJSONを返してみる。
DB接続、ORMの取扱いなどは次回へ回す。
環境
- OSX HighSierra
- Homebrew
- JDK1.8
sbt導入
brew install sbt
プロジェクト作成
sbt new playframework/play-scala-seed.g8
筆者はIntelliJ IDEAのプロジェクト作成を使った。
Hello World
作成したプロジェクト直下で sbt run
を実行。
長めのビルドが始まり、完了すると localhost:9000
でWelcomeページが見れる。
JSON返却
HomeControllerで下のように追記。
app/controllers/HomeController
package controllers
import javax.inject._
import play.api.mvc._
+ import play.api.libs.json._
/**
* This controller creates an `Action` to handle HTTP requests to the
* application's home page.
*/
@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
/**
* Create an Action to render an HTML page with a welcome message.
* The configuration in the `routes` file means that this method
* will be called when the application receives a `GET` request with
* a path of `/`.
*/
def index = Action {
Ok(views.html.index("Your new application is ready."))
}
+ def api = Action {
+ Ok(Json.toJson(Map("message" -> "Hello Play")))
+ }
}
再度 sbt run
でリビルドする。
localhost:9000/api
で {"message": "Hello Play"}
が返されてるのを確認。
参考