LoginSignup
4
1

More than 5 years have passed since last update.

はじめてのScala Play Framework APIでJSON返却

Last updated at Posted at 2018-07-26

初めて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"} が返されてるのを確認。

参考

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1