Consuming the Twitter API in Scala with Scribe

May 09, 2011

Nuevos is a minimalist Twitter client which highlights unread tweets. Its purpose is to provide at a glance an easy way to get updates of one's own timeline.

Nuevos remembers which tweets you have most recently seen regardless of which Web browser you use, so that state is kept up to date irrespective of the computer (or phone) you use.

Nuevos is currently quite beta, but seems to be stable enough for a few users.

Scribe is an OAuth library for Java which comes with built-in support for many APIs.

Scribe is configured by instantiating an OAuthService:

def service: OAuthService = new ServiceBuilder()

The consumer key, consumer secret, and auth callback are all assigned by Twitter to an application through the Twitter developers site.

Twitter API calls must be signed via OAuth, which is a multi-step process. First, a user needs to authenticate and grant access with Twitter:

def requestToken(): Token =

def getAuthUrl(requestToken: Token): String =

Once access has been granted by the user, his access token is needed to sign future API calls:

def getAccessToken(requestToken: Token, verifierCode: String): Token = {
  val verifier: Verifier = new Verifier(verifierCode);
  service.getAccessToken(requestToken, verifier);

Now the application can use this access token to make signed API calls:

def get(url: String, accessToken: Token): String = {
  request(Verb.GET, url, accessToken)

def request(verb: Verb, url: String, accessToken: Token): String = {
  val request: OAuthRequest = new OAuthRequest(verb, url)
  service.signRequest(accessToken, request)
  val response: Response = request.send
  if (response.getCode == 401) throw new UnauthorizedException

def homeTimeline(accessToken: Token): NodeSeq = {
  val url = ""
  val response: String = get(url, accessToken)
  val statuses = XML.loadString(response)
  statuses \ "status"

That's about it! Calling homeTimeline above will return a sequence of nodes, each of which contains a tweet (or "status" in Twitter API parlance).

I built this code into a minimalistic Twitter client designed to quickly show me what new tweets have been added to my home timeline. The result is a simple Scalatra application which looks a little like the following. Note that for the screenshots below, I changed my API call to user_timeline so that only my own tweets would show.

Initial authentication and access grant
Initial authentication and access grant
Upon first access, all tweets are unread
Upon first access, all tweets are unread
Clicking on a tweet reveals extra information about it
Clicking on a tweet reveals extra information about it
Subsequent access shows that all tweets have been read
Subsequent access shows that all tweets have been read