Getting an OAuth Token in Python

Get the Python oauth2 Library

The oauth2 library can be downloaded from GitHub.  Install oauth2 on your computer and view the client example here

Initialize the OAuth Client

In the first section of the code, you need to replace CONSUMER_KEY and CONSUMER_SECRET with the values for your application's key.

1
2
3
4
5
6
7
import oauth2 as oauth
import urlparse 
 
consumer_key           = "CONSUMER_KEY"
consumer_secret        = "CONSUMER_SECRET"
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)

Get a Request Token

Once all the variables are set up, the first item of business is getting a request token.

1
2
3
4
5
6
request_token_url      = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200':
    raise Exception("Invalid response %s." % resp['status'])
 
request_token = dict(urlparse.parse_qsl(content))

The sample code outputs some text to let you know you're on the right track:

1
2
3
4
print "Request Token:"
print "    - oauth_token        = %s" % request_token['oauth_token']
print "    - oauth_token_secret = %s" % request_token['oauth_token_secret']
print 

Redirect to the Provider

Since we are using a command line interface for this process, we will not include a callback in the redirect. We'll discuss how to use callbacks in later portions of the guide.

1
2
3
4
authorize_url =      'https://api.linkedin.com/uas/oauth/authorize'
print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])
print 

For this out-of-browser path, we'll need to ask the user to input the PIN by hand to verify that they've accepted.

1
2
3
4
accepted = 'n'
while accepted.lower() == 'n':
    accepted = raw_input('Have you authorized me? (y/n) ')
oauth_verifier = raw_input('What is the PIN? ')

Get the Access Token

1
2
3
4
5
6
7
8
9
10
11
12
13
14
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
 
resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))
 
print "Access Token:"
print "    - oauth_token        = %s" % access_token['oauth_token']
print "    - oauth_token_secret = %s" % access_token['oauth_token_secret']
print
print "You may now access protected resources using the access tokens above."
print