How to login with Twitter API using Python

Ahmad Bilesanmi
5 min readJan 30, 2018

When you have an application that requires users to login using their Twitter accounts, you will have to implement the Twitter Sign in API. The challenge with this is that the implementations of Twitter Sign in is based of OAuth, which can seem overly complicated.

This tutorial will be using a library called Requests-OAuthlib to ease the process of developing an application that allows users to be able to sign in easily with their Twitter accounts.

  1. Register as a developer on Twitter: You have to register as developer on Twitter. This can be done from this link
  2. Create an app on the Twitter platform: Here, you can create your app with all the required settings for the app to enable you get details from your users when they sign in with their accounts. Ensure you fill in the required fields. The callback URL can be the URL of the landing page for your application or company. It is the webpage that Twitter is directed to after users have successfully authenticated to your app. Ensure you check the option that says “Allow this application to be used to Sign in with Twitter.”
  3. Get your keys: After you have created your app, you can retrieve your Consumer Key and Consumer Secret from the Keys and Access Tokens tab of your application page. If you want other users to sign in to your app with their accounts, you don’t need to bother about the Access Token section.
  4. Check your permissions: If you need to retrieve the user’s email in order to register her on your application then you have to change your permissions on the Permissions tab on the application page. Ensure your access type is “Read Only” if you want to get the email. Also, in the Additional Permissions section, check the option “Request email address from users.”
  5. Create your python application: Create a Python application with any editor of your choice.
  6. Install the Requests-OAuthlib library:

pip install requests-oauthlib

7. Get the request token:

from requests_oauthlib import OAuth1Sessionconsumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
def get_resource_token():
#create an object of OAuth1Session
request_token = OAuth1Session(client_key=consumer_key, client_secret=consumer_secret)
# twitter endpoint to get request token
url = 'https://api.twitter.com/oauth/request_token'
# get request_token_key, request_token_secret and other details
data = request_token.get(url)
# split the string to get relevant data
data_token = str.split(data.text, '&')
ro_key = str.split(data_token[0], '=')
ro_secret = str.split(data_token[1], '=')
resource_owner_key = ro_key[1]
resource_owner_secret = ro_secret[1]
resource = [resource_owner_key, resource_owner_secret]
return resource

Let me explain what I have up there. We have our consumer key and secret from our Twitter application page.

In our get_resource_token method, we create an object of OAuth1Session and pass our consumer key and secret as client_key and client_secret respectively. According to the requests-oauthlib documentation, when creating an object of OAuth1Session,we are to add the resource_owner_key and resource_owner_secret. However, we don’t have those yet, so we won’t use them in the object creation.

After retrieving the data string, we split in order to get the value for the request token key and request token secret which we will use later.

8. Get oauth_verifier by redirecting the user: Now that we have got the request_token_key, we will be passing it together with the authentication endpoint. Here we are redirecting the user to Twitter where they will login, thereby agreeing to the permissions your application has on their accounts.

https://api.twitter.com/oauth/authenticate?oauth_token=8pDKRgAAAAAA4FGhAAABYSh-IsU

This is how the URL will look. The oauth_token parameter refers to the request_token_key retrieved from the last step.

Note: The above oauth_token would not work and its just used as a description here.

The link will lead the user to the Twitter page. Once the user accepts the permissions and logs in, Twitter redirects to your callback URL with some new information. The key we are interested in is the oauth_verifier, get the value and we will use it later. This is how a returned URL would look:

https://www.flaregh.com/?oauth_token=DnrJdgAAAAAA4FGhAAABYTJGPqQ&oauth_verifier=prTiNdFPARNRwLHwOPH2AfV4hqEbdgTj

9. Get the access token:

Now that we have got the oauth_verifier, its time to get our access token. To do this we need the access token endpoint:

https://api.twitter.com/oauth/access_token

With this we can create another method to help us get our access token:

def twitter_get_access_token(verifier, ro_key, ro_secret):
oauth_token = OAuth1Session(client_key=consumer_key,
client_secret=consumer_secret,
resource_owner_key=ro_key,
resource_owner_secret=ro_secret)
url = 'https://api.twitter.com/oauth/access_token'
data = {"oauth_verifier": verifier}

access_token_data = oauth_token.post(url, data=data)
print(access_token_data.text)
access_token_list = str.split(access_token_data.text, '&')
return access_token_list

What we have done here is to create a method that accepts the oauth_verifier, resource_owner_key and resource_owner_secret (that we got from step 7). We create an object of OAuth1Session that accepts four arguments for its initialization; it takes the consumer key, consumer secret, resource owner key and resource owner secret. data is a dictionary that we pass along with the url when we are calling the post method on oauth_token.

access_token_data now holds a Response object. The text attribute will hold a data string that looks like what we have below:

oauth_token=618540274–4jdk16Eolle9SbMmQIdu8O9nUwRsxRXeJJoVfGbN&oauth_token_secret=esqBoIAxbKr3sH6mvig4ZEPhyKQWk4BLShq8xDGSUWoIA&user_id=610000000&screen_name=femibilesanmi&x_auth_expires=0

We then split this string using the str.split() function into its various components and return it as access_token_list. This means access_token_list will be holding oauth_token, oauth_token_secret, user_id, screen_name and x_auth_expires .

10. Get user data: With our access token and access token secret, we can now get user data from Twitter. Lets’s look at our final function:

def twitter_get_user_data(access_token_list):
access_token_key = str.split(access_token_list[0], '=')
access_token_secret = str.split(access_token_list[1], '=')
access_token_name = str.split(access_token_list[3], '=')
access_token_id = str.split(access_token_list[2], '=')
key = access_token_key[1]
secret = access_token_secret[1]
name = access_token_name[1]
id = access_token_id[1]
oauth_user = OAuth1Session(client_key=consumer_key,
client_secret=consumer_secret,
resource_owner_key=key,
resource_owner_secret=secret)
url_user = 'https://api.twitter.com/1.1/account/verify_credentials.json'
params = {"include_email": 'true'}
user_data = oauth_user.get(url_user, params=params)

return user_data.json()

Here, we passed the access_token_list as an argument to the function. In the function, we further split each string into its key and value. we create another object of OAuth1Session, taking consumer key, consumer secret, access_token_key and access_token_secret.

Note: For the resource_owner_key and resource_owner_secret, we are passing the access_token_key and access_token_secret that we got from step 9.

The endpoint we are using to retrieve user details is :

https://api.twitter.com/1.1/account/verify_credentials.json

If the user’s email is important for your application, then you have to include the params in the get request method.

The full code can be found here

Please let me know if you have any issues with the code or there are ways I can improve the code or write up to make it easy for others to learn from.

Thank you for your time.

--

--