Example using Python Oauth2 to access Twitter


Here is a quick example how to use Python Oauth2 to gain access into Twitter account. We need to install “oauth2” python package first by :

1
pip install oauth2

Then here is a quick example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import oauth2 as oauth
import json

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

# Request token URL for Twitter.
request_token_url = "https://api.twitter.com/oauth/request_token"

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

# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
print json.dumps(resp, indent=4)
print json.dumps(content, indent=4)

It will showing results :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
    "status": "200",
    "content-length": "144",
    "content-location": "https://api.twitter.com/oauth/request_token?oauth_body_hash=xxxxx&oauth_nonce=48355082&oauth_timestamp=1361601089&oauth_consumer_key=xxxx&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_signature=xxxxLzwwvw1NtMvuD0PKA%3D",
    "x-transaction": "xxxx36f9200946491",
    "set-cookie": "k=xx.37xx0.136xxx509550; path=/; expires=Sat, 02-Mar-13 06:31:30 GMT; domain=.twitter.com, guest_id=v1%3A136xxx052057281; domain=.twitter.com; path=/; expires=Mon, 23-Feb-2015 18:31:30 GMT, _twitter_sess=BAh7CDoPY3JlxxxxxZjg3ZGYzMjhjYTdiNzM2MDQ1–1bxxxxx8ec0a; domain=.twitter.com; path=/; HttpOnly",
    "expires": "Tue, 31 Mar 1981 05:00:00 GMT",
    "x-mid": "b892643948470824023ffee4beed31c48388104a",
    "server": "tfe",
    "last-modified": "Sat, 23 Feb 2013 06:31:30 GMT",
    "x-runtime": "0.02175",
    "etag": ""d657e3e63axxxx83cea7d"",
    "pragma": "no-cache",
    "cache-control": "no-cache, no-store, must-revalidate, pre-check=0, post-check=0",
    "date": "Sat, 23 Feb 2013 06:31:30 GMT",
    "x-frame-options": "SAMEORIGIN",
    "content-type": "text/html; charset=utf-8",
    "-content-encoding": "gzip",
    "vary": "Accept-Encoding"
}
"oauth_token=xxxxxxxxxxxx&oauth_token_secret=xxxxx&oauth_callback_confirmed=true"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.