REST example with PlayFramework Scala

Scala is an incredible language!! It is ridiculously concise and is packed full of wonderful features that combine to provide a pure functional and pure oo language. Currently, I am working on two Scala Play2 projects and I couldn’t be happier.

In this post, we will build a super simple REST service using Play and Scala. Once again, we’ll go with the Cars theme!

Prerequisites:
– Download and Install the Typesafe Activator
– Launch activator ui and install the play-scala template. (This will provide the scaffolding for our Play app)

Defining REST endpoints
Play provides a very straight forward mechanism for defining routes. To do so, simply define each route along with a mapping to its handler or Controller class. Here we define the routes for our Cars example:

Open conf/routes and add the following:

[code language=”Scala”]
# Get a car by its id
GET /api/cars/:id controllers.CarController.get(id: Long)
# Get all cars
GET /api/cars controllers.CarController.get
# Create a new car
POST /api/cars controllers.CarController.create
[/code]

Defining routes is not only straightforward, but it also doubles as documentation. The routes file provides a clear and concise definition of our REST endpoints.

Defining endpoint behavior using Controllers
Currently, we have a REST API, however the API doesn’t do anything. To define behavior for each of our endpoints, we must implement the functions that map to our routes. Typically, this behavior is defined in a controller object that extends the play.api.mvc.Controller trait. Extending the <code>Controller</code> trait is not required, however it provides many of useful helpers e.g. Action, Action.async, etc.

Create a new object controllers.CarController in the app directory.
Implement the following methods in CarController:

[code language=”Scala”]
import play.api.mvc._

object CarController extends Controller {

def create = Action { implicit request => {
val response = Json.obj("make" -> "Audi", "model" -> "A5")
Ok(response)
}

def get = Action { implicit request => {
val response = Json.arr(
Json.obj("make" -> "Audi", "model" -> "A5"),
Json.obj("make" -> "BMW", "model" -> "335"))
Ok(response)
}

def get(id: Long) = Action { implicit request => {
val response = Json.obj("make" -> "Audi", "model" -> "A5"))
Ok(response)
}
[/code]

The above example is not all the exciting. As you can see, we return static JSON and our create function does not actually create anything.

In my next post, we will further explore this example by extending its current behavior to interact with MongoDb using the Play ReactiveMongo  plugin. Furthermore, in a future post, we’ll also create some tests using Specs2

Test it

Thank you!

You may also like...