How to send JSON POST data to a REST url

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 15.11, “How to send JSON POST data to a REST url.”


When writing Scala code, you want to send JSON data (or other data) to a POST URL, either from a standalone client, or when using a framework that doesn’t provide this type of service.

How to load an XML URL in Scala (contents of an XML web page)

Scala XML FAQ: How do I load an XML URL in Scala? (How do I read/download the contents of an XML URL in Scala?)

To load the contents of an XML URL (web page) in Scala, such as an RSS news feed or RESTful web service, just use the load method of the Scala XML class:

val xml = XML.load("")

Here's an example of what this looks like in the Scala REPL:

A Scala JSON (Gson) HTTP POST RESTful client example

While working on a Scala project recently I created the following example Scala code to test a variety of things, including:

  • Scala case classes
  • The Apache HttpClient classes, including HttpPost
  • Creating JSON with Gson
  • Sending the JSON object/string to my POST RESTful server

Given that brief introduction, here's the source code for my Scala HTTP client, which uses POST (Apache HttpPost) to send data to a RESTful web service:

Syndicate content