Actions
As explained in the routes guide, an action is the code that handles a route.
When an incoming request matches a route, that route’s action is executed.
Default behavior
Each route is followed by an action. An Action may return any value, which is then rendered to the response according to the following rules.
- ActionResult
- Sets status, body and headers. After importing
org.scalatra.ActionResult._
, you can return 200 OK, 404 Not Found and other responses by referencing them by their descriptions. See the ActionResult example code (below) for an example.
- Array[Byte]
- If no content-type is set, it is set to
application/octet-stream
. The byte array is written to the response's output stream. - NodeSeq
- If no content-type is set, it is set to
text/html
. The node sequence is converted to a string and written to the response's writer. - Unit
- This signifies that the action has rendered the entire response, and no further action is taken.
- Any
- For any other value, if the content type is not set, it is set to
text/plain
. The value is converted to a string and written to the response's writer.
Custom action behavior
The behavior for the types in the above chart, or for types not in the chart at all,
may be customized for these or other return types by overriding renderResponse
.
ActionResult example
get("/file/:id") {
fileService.find(params("id")) match {
case Some(file) => Ok(file)
case None => NotFound("Sorry, the file could not be found")
}
}
In this example, ActionResult is being used conditionally to give back different
response codes based on what’s happened in the action. If a file
is found
by the hypothetical fileService
, the action returns Ok(file)
. This means
that the response was successful, and there’s a response code of 200.
If the fileService
didn’t find a file, the action returns NotFound
and
a message. The NotFound
sets a response code of 404.
There are several dozen possible responses in Scalatra, if you want to see all of them and find out what response codes they produce, the easiest way is to look at the ActionResult source code.