15.7. Accessing Scalatra Web Service GET Parameters

Problem

When creating a Scalatra web service, you want to be able to handle parameters that are passed into a method using a GET request.

Solution

If you want to let parameters be passed into your Scalatra servlet with a URI that uses traditional ? and & characters to separate data elements, like this:

http://localhost:8080/saveName?fname=Alvin&lname=Alexander

you can access them through the implicit params variable in a get method:

/**
 * The URL
 * http://localhost:8080/saveName?fname=Alvin&lname=Alexander
 * prints: Some(Alvin), Some(Alexander)
 */
get("/saveName") {
  val firstName = params.get("fname")
  val lastName = params.get("lname")
  <p>{firstName}, {lastName}</p>
}

However, Scalatra also lets you use a “named parameters” approach, which can be more convenient, and also documents the parameters your method expects to receive. Using this approach, callers can access a URL like this:

http://localhost:8080/hello/Alvin/Alexander

You can handle these parameters in a get method like this:

get("/hello/:fname/:lname") {
  <p>Hello, {params("fname")}, {params("lname")}</p>
}

As mentioned, a benefit of this approach is that the method signature documents the expected parameters.

With this approach, you can use wildcard characters for other needs, such as when a client needs to pass in a filename path, where you won’t know the depth of the path beforehand:

get("/getFilename/*.*") {
  val data = multiParams("splat")
  <p>{data.mkString("[", ", ", "]"

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.