Querying web APIs

The easiest way of querying a web API from Scala is to use Source.fromURL. We have already used this in Chapter 4, Parallel Collections and Futures, when we queried the "Markit on demand" API. Source.fromURL presents an interface similar to Source.fromFile:

scala> import scala.io._
import scala.io._

scala> val response = Source.fromURL(
  "https://api.github.com/users/odersky"
).mkString
response: String = {"login":"odersky","id":795990, ...

Source.fromURL returns an iterator over the characters of the response. We materialize the iterator into a string using its .mkString method. We now have the response as a Scala string. The next step is to parse the string with a JSON parser.

Get Scala: Guide for Data Science Professionals 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.