15.5. Creating Web Services with Scalatra

Problem

You want to be able to build new web services with Scalatra, a lightweight Scala web framework similar to the Ruby Sinatra library.

Solution

The recommended approach to create a new Scalatra project is to use Giter8, a great tool for building SBT directories for new projects.

Assuming you have Giter8 installed, use the g8 command to create a new project with a Scalatra template:

$ g8 scalatra/scalatra-sbt
organization [com.example]: com.alvinalexander
package [com.example.app]: com.alvinalexander.app
name [My Scalatra Web App]:
scalatra_version [2.2.0]:
servlet_name [MyScalatraServlet]:
scala_version [2.10.0]:
version [0.1.0-SNAPSHOT]:

Template applied in ./my-scalatra-web-app

When Giter8 finishes, move into the new directory it created:

$ cd my-scalatra-web-app

Start SBT in that directory, and then issue the container:start command to start the Jetty server:

$ sbt

> container:start
// a lot of output here ...
[info] Started SelectChannelConnector@0.0.0.0:8080
[success] Total time: 11 s, completed May 13, 2013 4:32:08 PM

Then use the following command to enable continuous compilation:

> ~ ;copy-resources;aux-compile
1. Waiting for source changes... (press enter to interrupt)

That command is nice; it automatically recompiles your source code when it changes.

The Jetty server starts on port 8080 by default. If you switch to a browser and go to the URL http://localhost:8080/, you should see some default “Hello, world” output, indicating that Scalatra ...

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.