15.8. Accessing POST Request Data with Scalatra

Problem

You want to write a Scalatra web service method to handle POST data, such as handling JSON data sent as a POST request.

Solution

To handle a POST request, write a post method in your Scalatra servlet, specifying the URI the method should listen at:

post("/saveJsonStock") {
  val jsonString = request.body
  // deserialize the JSON ...
}

As shown, access the data that’s passed to the POST request by calling the request.body method.

The Discussion shows an example of how to process JSON data received in a post method, and two clients you can use to test a post method: a Scala client, and a command-line client that uses the Unix curl command.

Discussion

Recipe 15.3 shows how to convert a JSON string into a Scala object using the Lift-JSON library, in a process known as deserialization. In a Scalatra post method, you access a JSON string that has been POSTed to your method by calling request.body. Once you have that string, deserialize it using the approach shown in Recipe 15.3.

For instance, the post method in the following StockServlet shows how to convert the JSON string it receives as a POST request and deserialize it into a Stock object. The comments in the code explain each step:

package com.alvinalexander.app

import org.scalatra._
import scalate.ScalateSupport
import net.liftweb.json._

class StockServlet extends MyScalatraWebAppStack {

  /**
   * Expects an incoming JSON string like this:
   * {"symbol":"GOOG","price":"600.00"}
   */
  post("/saveJsonStock" ...

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.