Twitter REST API from Scala and Java using signpost

If you’ve read some other articles on this blog you might know that I like creating visualizations of various datasets. I’ve just started a small project where I want to visualize some data from Twitter. For this I want to retrieve information about followers and profile information directly from twitter. I actually started looking for a set of all twitter accounts, but could only find one that was two years old. So, only option left, directly access the twitter API and get the data myself.

There are a couple of open source libraries out that we can use directly from Scala (or java) but as far as I could see they use the old v1 API and not the v1.1 API. The old API has a very strict data rate limit, which is a bit lighter in the new API. And besides that I’m more interested in the raw data and parsing the returning JSON isn’t that hard with Scala (or Java for that matter).

Register an application at twitter

First thing to do, and easiest way to get started is registing a new application for your twitter account. Go to and create a new application. Don’t worry about the urls, since we won’t be using the OAuth callback mechanism:

Depending on what you want to do with the API you need to give additional permissions to this app. Default is ‘read-only’, if you want to allow your new application to post or access your direct messages you need to update the permissions. This is done from the settings page of your application:

Once you’ve created the application and setup the correct permissions you can generate an access token. Doing this will avoid having to go through the complete OAuth dance. You do this by going to your new app details and at the bottom select the ‘create my access token’ option.

Now you’ll have a set of tokens (see the details part of your applications):

We’ll use these tokens to authenticate the requests we’ll make to twitter.

Using a OAuth library

The OAuth protocol is a pretty good documented protocol, but implementing it yourself is a lot of work and very error-prone. Luckily there are many OAuth libraries that can help you. I’ve tried a couple and the one that’s most easy to use (at least for me) was signpost. The examples below show how to do this from Scala, but you can follow the same approach for Java.

First the dependencies. I’ve used sbt and from signpost I use the client with support for HTTP commons. In sbt add the following:

libraryDependencies ++= Seq(
 'oauth.signpost' % 'signpost-core' % '1.2',
 'oauth.signpost' % 'signpost-commonshttp4' % '1.2', 
 'org.apache.httpcomponents' % 'httpclient' % '4.2',

For maven you can use the same libraries. Next we can write a simple test to see if everything is working. In java it looks like this:

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Tw {
   static String AccessToken = 'access token for your app';
   static String AccessSecret = 'access secret for your app';
   static String ConsumerKey = 'consumer key for your app';
   static String ConsumerSecret = 'consumer secret for your app';
  * @param args
 public static void main(String[] args) throws Exception {
  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
        consumer.setTokenWithSecret(AccessToken, AccessSecret);
        HttpGet request = new HttpGet('');
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println(statusCode + ':' + response.getStatusLine().getReasonPhrase());

And in Scala it looks pretty much the same:

import org.apache.http.client.HttpClient
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpGet
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer
object TwitterPull {
   val AccessToken = 'access token for your app';
   val AccessSecret = 'access secret for your app';
   val ConsumerKey = 'consumer key for your app';
   val ConsumerSecret = 'consumer secret for your app';
  def main(args: Array[String]) {
  val consumer = new CommonsHttpOAuthConsumer(ConsumerKey,ConsumerSecret);
  consumer.setTokenWithSecret(AccessToken, AccessSecret);
     val request = new HttpGet('');
     val client = new DefaultHttpClient();
     val response = client.execute(request);

When you run this the output will look something like this:


If you get a 403 check whether the tokens match.

Happy coding and don’t forget to share!

Reference: Access the Twitter REST API (v1.1) from Scala and Java using signpost from our JCG partner Jos Dirksen at the Smart Java blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply

two × = 12

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books