Sensis Developer Centre - SAPI Forums

API Forum

RSS Feed

Scala APIExample

    • Hound
    • Topic created 9 years ago

    Here's a Scala transliteration of the Java API Example. It may not be 100% correct as I don't have my API key yet, but the parsing portion works.

    This example requires Twitter's JSON library from

    It is not quite idiomatic Scala, but it's close enough. It returns a List of Listings rather than printing them out.

    There's a lot of annoying casting involved after the JSON parsing. I suspect the SJSON library will do this better, but I'm yet to grok it. If it improves the code, then I'll update this sample.

    import io.Source
    import com.twitter.json.Json

    case class Listing(name: String, address: String)
    class SensisApiExample {
    private val apiKey = "..."

    def searchByType(query: String, location: String) = {
    val url = ""
    .format(apiKey, encode(query, "UTF-8"), encode(location, "UTF-8"))
    val json = Json.parse(Source.fromURL(url).mkString).asInstanceOf[Map[Any,Any]]
    val (code, message) = (json("code").asInstanceOf[Int], json("message").asInstanceOf[String])
    println("Total results found: %d".format(json("totalResults")))

    def parse(results: List[Map[Any, Any]]) = {{map =>
    val name = map("name").asInstanceOf[String]
    val place = map("primaryAddress").asInstanceOf[Map[Any,Any]].apply("addressLine").asInstanceOf[String]
    Listing(name, place)

    val results = code match {
    case 200 => parse(json("results").asInstanceOf[List[Map[Any,Any]]])
    case 206 => {
    println("Note: %s".format(message))
    case _ => throw new RuntimeException("API returned error: %s, code: %d".format(message, code))

    Message edited by Hound 9 years ago


  1. Hound9 years ago

    See for better formatting

[ Page 1 of 1 ]