Tutorial: Play Framework 2 with Scala, Anorm, JSON, CoffeeScript, jQuery & Heroku

Play Framework 2 RC2 has been released and it is quickly becoming a mature and productive way to build modern web apps. Lets walk through building a quick app with Play 2, Scala, Anorm, JSON, CoffeeScript, and jQuery. Once the app works locally we will deploy it on the cloud with Heroku. (Note: This is the Play 2 + Scala version of my Play 1 + Java tutorial.) You can grab the completed source from GitHub.

Step 1) Download and install Play 2 RC2

Step 2) Create a new application:

play new foobar

When prompted select to use Scala as the language.

Step 3) In the newly created “foobar” directory generate the IDE config files if you’d like to use one. For IntelliJ, run:

play idea

Note: This generates an iml file which is not directly importable as a project. Instead you need to create a new project without a module and then import the module from the generated iml file. If you need help with this, follow instructions 8 - 10 in my Play 1 + Scala IntelliJ article.

For Eclipse, run:

play eclipsify

Step 4) Start the Play server:

play run

Test that it works by visiting: http://localhost:9000

Step 5) Play 2 with Scala doesn’t provide an ORM by default. Instead the default RDBMS persistence provider is Anorm (Anorm is Not an Object Relational Mapper). This simple application will just have one persistence object: a Bar with a primary key and a name. Anorm requires a SQL schema creation / destruction script since it doesn’t do auto schema creation. Create a new file named “conf/evolutions/default/1.sql” containing:

# --- First database schema

# --- !Ups

create table bar (
  id                        SERIAL PRIMARY KEY,
  name                      varchar(255) not null
);

# --- !Downs

drop table if exists bar;

Anorm can use a Scala “case class” as a Value Object and a singleton object as the persistence / CRUD interface. Create the Bar case class and object in a file named “app/models/Bar.scala” with the following contents:

package models

import play.api.db._
import play.api.Play.current

import anorm._
import anorm.SqlParser._

case class Bar(id: Pk[Long], name: String)

object Bar {

  val simple = {
    get[Pk[Long]]("id") ~
    get[String]("name") map {
      case id~name => Bar(id, name)
    }
  }

  def findAll(): Seq[Bar] = {
    DB.withConnection { implicit connection =>
      SQL("select * from bar").as(Bar.simple *)
    }
  }

  def create(bar: Bar): Unit = {
    DB.withConnection { implicit connection =>
      SQL("insert into bar(name) values ({name})").on(
        'name -> bar.name
      ).executeUpdate()
    }
  }

}

The “simple” var provides a basic row parser that maps a database row values to the Bar case class. The “findAll” and “create” static functions just do the regular data access stuff. Notice how the “findAll” function uses the “simple” row parser to turn each row into a Bar.

Step 6) Configure the default data source to use an in-memory h2 database by adding the following values to the “conf/application.conf” file:

db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"

Step 7) Create an Application controller function that will translate a HTTP POST into a Bar and then save it to the database by updating the “app/controllers/Application.scala” file to be:

package controllers

import play.api.data.Form
import play.api.data.Forms.{single, nonEmptyText}
import play.api.mvc.{Action, Controller}
import anorm.NotAssigned

import models.Bar


object Application extends Controller {

  val barForm = Form(
    single("name" -> nonEmptyText)
  )

  def index = Action {
    Ok(views.html.index(barForm))
  }

  def addBar() = Action { implicit request =>
    barForm.bindFromRequest.fold(
      errors => BadRequest,
      {
        case (name) =>
          Bar.create(Bar(NotAssigned, name))
          Redirect(routes.Application.index())
      }
    )
  }
  
}

The “barForm” maps request parameters to a Form object and can apply validations to the incoming data. The “addBar” static function handles a request and attempts to map the request parameters to the “barForm”. If it fails then the controller returns a BadRequest. If it succeeds then the Bar’s name is used to construct a new “Bar” which is saved into the database and a redirect to the index page is sent. The index function has been changed to pass the “barForm” to the template which will be updated in Step 9.

Step 8) Create a new route to map POST requests to the “/addBar” URL to the “Application.addBar” function by adding the following line to the “conf/routes” file:

POST    /addBar                     controllers.Application.addBar

Step 9) Update the “app/views/index.scala.html” template to take the Form parameter, extend the “main” template, and then use the Play 2 form helper to render the form on the web page:

@(form: play.api.data.Form[String])

@main("Welcome to Play 2.0") {

    @helper.form(action = routes.Application.addBar) {
        @helper.inputText(form("name"))
        <input type="submit" />
    }

}

In your browser load http://localhost:9000, apply the database evolution, and test the form. If everything works when you submit the form you should just be redirected back to the index page.

Step 10) Create a JSON service to get all of the bars by adding a new function to the “app/controllers/Application.scala” file:

import com.codahale.jerkson.Json
  
  def listBars() = Action {
    val bars = Bar.findAll()

    val json = Json.generate(bars)

    Ok(json).as("application/json")
  }

This new function returns the list of “Bar” objects from “Bar.findAll()” as serialized JSON.

Add a new GET request handler for requests to “/listBars” by adding the following to the “conf/routes” file:

GET     /listBars                   controllers.Application.listBars

Try it out by opening http://localhost:9000/listBars in your browser. You should see the Bar you created in Step 9.

Step 11) Create a new CoffeeScript file that will use jQuery to fetch the JSON serialized Bars and add each one to the page by creating a new “app/assets/javascripts/index.coffee” file containing:

$ ->
  $.get "/listBars", (data) ->
    $.each data, (index, item) ->
      $("#bars").append "

<li>
  Bar " + item.name + "
</li>"

This CoffeeScript uses jQuery to make a GET request to “/listBars”, iterate through the returned data, and add each item to the “bars” element on the page (which will be added in Step 12).

Step 12) Update the “app/views/index.scala.html” template to use the index.js script that is automatically compiled from the CoffeeScript source by adding the following to the “main” block:

<ul id="bars">
  
</ul>

In your browser load http://localhost:9000 and verify that the bars are being displayed on the page and that adding new bars works as expected.

Great! You just built a Play 2 app with Scala, Anorm, JSON, CoffeeScript, and jQuery! All of the source code for this example is on GitHub. Now lets deploy it on the cloud with Heroku.

Step 1) Create an account on Heroku.com, install the Heroku Toolbelt, install git, and then login to Heroku from the command line:

heroku login

If this is the first time you’ve done this then new SSH keys for git will be created and associated with your Heroku account.

Step 2) Each application on Heroku has a Postgres database for testing. To use that database when running on Heroku we need to configure it. There are a few ways to do that with Play 2 but the easiest will be to override the database settings with the startup command line - which we will setup in Step 3. Before we do that we need to specify the Postgres JDBC driver as a project dependency. In the “project/Build.scala” file set the “appDependencies” like so:

val appDependencies = Seq(
      "postgresql" % "postgresql" % "9.1-901-1.jdbc4"
    )

Step 3) To tell Heroku what process to run we need to create a file named “Procfile” (case sensitive) in the project’s root directory containing:

web: target/start -Dhttp.port=$PORT -DapplyEvolutions.default=true -Ddb.default.driver=org.postgresql.Driver -Ddb.default.url=$DATABASE_URL

Play 2 uses the Scala Build Tool (SBT) to build the project. When the project is deployed to Heroku the “sbt stage” command is run to compile the project. That process generates a “target/start” script that sets the Java classpath and starts the Play server. Heroku tells our application what HTTP port to listen on using the “PORT” environment variable so the “http.port” Java property is set accordingly. Also the default way to provide database (and other resource) connection strings to an application on Heroku is through environment variables. The DATABASE_URL environment variable will contain the database host, name, username, and password. So the “db.default.url” property is set with that value. Also the driver is set to the Postgres JDBC driver class.

Step 4) Heroku uses git as a means to uploading applications. Whether or not you use git for your SCM tool you can use git as the tool to upload an app to Heroku. In the root directory of your project create git repo, add the files to it, and then commit the files:

git init
git add Procfile app conf project public
git commit -m init

Note: Instead of doing a selective “git add” you can update the “.gitignore” file.

Step 5) Now we will provision a new application on Heroku using the Heroku CLI. Each application you create gets 750 free “dyno” hours per month. So as a developer you can use Heroku for free and only pay when you need to scale beyond one dyno. On the command line create a new application using the “cedar” stack:

heroku create -s cedar

This creates an HTTP endpoint and a git endpoint for your application. You can also use a custom name and point your own domain names at the application.

Step 6) The application is ready to be deployed to the cloud. From a command line do a “git push” to the master branch on Heroku:

git push heroku master

Once the files have been received by Heroku, Play Framework’s precompiler will be run, Heroku will assemble a “slug file”, and then the “slug” will be deployed onto a dyno.

Step 7) You can now open the application in your browser by navigating to the domain outputted following the “heroku create” or by simply running:

heroku open

You’ve deployed a Play 2 app with Scala, Anorm, JSON, CoffeeScript, and jQuery on the cloud with Heroku! For more details on how to use Heroku, check out the Heroku Dev Center. Let me know if you have any question.