scala.xml.Node, text/xml and Jersey: How to do REST with Scala

Scala has native support for xml in the language via scala.xml.Node

There is an excellent book called scala.xml on XML and Scala so this post won’t go into more detail.

Using the XML support in Scala makes it easy to write REST applications with Jersey. I’ve shown how to create JSON with a JsonBuilder in Scala before.

We need a Resource to handle our REST requests. As a response to a GET request on /helloWorld/xml we create a Scala XML node:

Jersey needs to know how to translate an object of scala.xml.Node to a HTTP response. This is usually done by implementing a MessageBodyWriter that maps an object and a mime type – scala.xml.Node and text/xml in this case – to a response.

Voila, we now get <message>Hello world</message> when calling /helloWorld/xml.

Thanks for listening.