How to use oauth-python-twitter

Using OAuth for authentication is quite different then using Basic Auth in many ways, first major difference is that one don’t know the username until it is requested from twitter after completing the authentication process.

Details

You will need following information to start.

  • Consumer Key
  • Consumer Secret

If you do not have above, you can request them from here: http://twitter.com/oauth_clients

The following are the steps that should be performed to authenticate user and get user information from twitter, the rest is same as using python-twitter.

  • Get the Request Token from twitter
  • Get Authorization URL
  • Get the Access Token from twitter
  • Get user information

Get the Request Token from twitter

twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
 
request_token = twitter.getRequestToken()

Get Authorization URL

using same request_token from previous step

authorization_url = twitter.getAuthorizationURL(request_token)

Now send the user to authorization URL, for allowing access to the application.

Get the Access Token from twitter

Once the user return from twitter, we need to request the access_token from twitter for futher aunthenticated api calls on behalf of user.

NOTE: Need to create the new instance of OAuthApi using request_token from first step.

twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, request_token)
 
access_token = twitter.getAccessToken()

Get user information

This api call was not present in python-twitter and the user info call expected that there we know the username before making call, but this is not the case with OAuth, so we have to request User Information so we can use it in our application.

NOTE: Need to create the new instance of OAuthApi using access_token from last step.

twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
 
user = twitter.GetUserInfo()

Now use the rest of python-twitter api calls as you used to use them with basic authentication, for more information see the wiki at:http://code.google.com/p/python-twitter