15.13. Creating a GET Request Web Service with the Play Framework

Problem

You want to create a GET request web service using the Play Framework, such as returning a JSON string when the web service URI is accessed.

Solution

When working with RESTful web services, you’ll typically be converting between one or more model objects and their JSON representation.

To demonstrate how a GET request might be used to return the JSON representation of an object, create a new Play project with the play new command:

$ play new WebServiceDemo

Respond to the prompts to create a new Scala application, and then move into the WebServiceDemo directory that’s created.

Next, assume that you want to create a web service to return an instance of a Stock when a client makes a GET request at the /getStock URI. To do this, first add this line to your conf/routes file:

GET   /getStock     controllers.Application.getStock

Next, create a method named getStock in the default Application controller (apps/controllers/Application.scala), and have it return a JSON representation of a Stock object:

package controllers

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

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

  def getStock = Action {
    val stock = Stock("GOOG", 650.0)
    Ok(Json.toJson(stock))
  }

}

That code uses the Play Json.toJson method. Although the code looks like you can create Stock as a simple case class, attempting to ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.