Operator Error

adventures in software development and continuous learning

Single User Access to the Twitter API Using OAuth

The Twitter API utilizes a 3-legged OAuth authentication process where an authenticated Twitter user can authorize a Twitter-based application to interact with their account and data. This is useful for applications that desire this ability, however what about a Twitter application that doesn’t care about other users and just wants to get down and dirty with public Twitter data? Thankfully the Twitter API provides a relatively easy way to do this!

NOTE: This guide assumes you are already familiar with the Twitter Developers page and have already registered an application. If you are unfamiliar with either of these concepts, its time to do some reading! If you are unsure what type of authentication process is correct for your application, head on over to the Obtaining Access Tokens article.

If you haven’t already generated access tokens for your application, follow this guide. Now that you have your access tokens, we can get cooking!

Grab the latest version of the python-oauth2 library. If you’re using another language, there might be an OAuth2 library available here.

1
$ git clone https://github.com/brosner/python-oauth2.git

Next, we’re gonna create a new python script called twitter.py.

twitter_api.pyView Gist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/python

import simplejson as json

import oauth2 as oauth

# Create your consumer with the proper key/secret.
consumer = oauth.Consumer(key="YOUR_CONSUMER_KEY",
                          secret="YOUR_CONSUMER_SECRET")

# Create your token with the proper key/secret.
token = oauth.Token(key="YOUR_ACCESS_TOKEN",
                    secret="YOUR_ACCESS_TOKEN_SECRET")

# Request token URL for Twitter.
rate_limit_url = "http://api.twitter.com/1/account/rate_limit_status.json"

# Create our client.
client = oauth.Client(consumer, token)

# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(rate_limit_url, "GET")

# Parse the JSON into a Python dictionary.
data = json.loads(content)

# Print hourly limits.
print "Hourly    => %3d" % (data['hourly_limit'])
print "Remaining => %3d" % (data['remaining_hits'])

Replace the following with your Twitter application OAuth values:

  • YOUR_CONSUMER_KEY
  • YOUR_CONSUMER_SECRET
  • YOUR_ACCESS_TOKEN
  • YOUR_ACCESS_TOKEN_SECRET

Now run the script and you should get the following output:

1
2
3
$ ./twitter.py
Hourly => 350
Remaining => 350

If you got 350 for your hourly limit, then you’ve successfully authenticated using OAuth (150 is the hourly limit for unauthenticated API requests)!

Now just replace the rate_limit_url string with another Twitter Resource API URI and have fun!

Comments