Authenticate the Twitter API with Python Example (Tweepy)

In this tutorial, you will learn how to authenticate the Twitter API using Python and Tweepy.

This tutorial is part of the complete guide on the Twitter API with Python.

What You Will Need

For this tutorial, you will need to have:

Join the Newsletter

    1. Python Installed. Read How to install Python with Anaconda

    Get a Twitter Developer Account

    To apply for a Twitter developer account, go to the Twitter Developer console and Apply for access.

    For the detailed steps, read: How to Apply for a Twitter Developer Account where I share answer ideas to complete the lengthy approval process.


    Create Your Application and Get Your Authentication Tokens

    Once, your account is approved, you will need to get your API credentials.

    You will need:

    • api_key
    • api_secret
    • access_token
    • access_secret

    The credentials will be used in a similar way to a username and password for your Application.

    Go to the Twitter Developer Portal, click on “Create project” and fill-in the form.

    For detailed steps of how to create your project and get your Twitter API keys, read: How to get Twitter API Credentials (API Keys)

    Twitter API Keys
    Twitter API Keys

    Install Tweepy

    For this tutorial, we will use the Tweepy wrapper to use the Twitter API.

    Get started by installing the package with either pip or conda in the Terminal or Command line:

    $ pip install tweepy
    
    $ conda install -c conda-forge tweepy
    

    Authenticate Your App

    import tweepy
    
    api_key = "..."
    api_secrets = "..."
    access_token = "..."
    access_secret = "..."
    
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler(api_key,api_secrets)
    auth.set_access_token(access_token,access_secret)
    
    api = tweepy.API(auth)
    
    try:
        api.verify_credentials()
        print('Successful Authentication')
    except:
        print('Failed authentication')
    
    

    Try the Twitter API

    You can now run your first Twitter API call.

    user = api.get_user('ChouinardJC')
    print(user.name)
    print(user.description)
    print(user.location)
    

    Advanced Authentication With Tweepy

    Let’s look at other types of authentication that are possible.

    Wait on Rate Limiting

    To let Tweepy handle rate limiting by itself, you can authenticate using wait_on_rate_limit=True, wait_on_rate_limit_notify=True, and compression=True.

    import tweepy
    
    api_key = "..."
    api_secrets = "..."
    access_token = "..."
    access_secret = "..."
    
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler(api_key,api_secrets)
    auth.set_access_token(access_token,access_secret)
    
    api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)
    

    Store Credentials in JSON

    To make sure that credentials are not committed to Github, here, I created a JSON file with my credentials that looks like this:

    {
        "api_key":"...",
        "api_secrets":"...",
        "access_token":"...",
        "access_secret":"...",
        "bearer_token":"..."
    }
    

    This way, I can add the JSON credential file to gitignore and it will not be uploaded to Github.

    Then, I created an authy.py file to handle the entire authentication process.

    import json
    import tweepy
    
    def authpy(credentials='credentials.json'):
        '''
        Authenticate to Twitter and get API object.
        '''
        creds = read_creds(credentials)
        key, secrets = creds['api_key'], creds['api_secrets']
        tk, tk_secrets = creds['access_token'], creds['access_secret']
    
        # Authenticate to Twitter
        auth = tweepy.OAuthHandler(key,secrets)
        auth.set_access_token(tk,tk_secrets)
    
        # Create the API object
        api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)
        return api
    
    def read_creds(filename):
        '''
        Read JSON file to load credentials.
        Store API credentials in a safe place.
        If you use Git, make sure to add the file to .gitignore
        '''
        with open(filename) as f:
            credentials = json.load(f)
        return credentials
    
    if __name__ == '__main__':
        credentials = 'credentials.json'
        api = authpy(credentials)
    

    Then, I can import the script from any program using:

    from authpy import authpy
    api = authpy('credentials.json')
    

    Authenticating a Heroku Twitter Bot

    Later, we are going to build a bot hosted on Heroku. To do so, we will need to set up environment variables to make sure that we don’t commit secrets to Github.

    We will set up the environment variables within the Heroku Dashboard.

    Then, will set up our credentials this way instead of using JSON.

    from os import environ
    import tweepy
    
    def authHeroku(key_var,secret_var,tk_var,tk_s_var):
        '''
        Authenticate to Twitter and get API object.
        '''
        key, secrets = environ[key_var], environ[secret_var]
        tk, tk_secrets = environ[tk_var], environ[tk_s_var]
    
        # Authenticate to Twitter
        auth = tweepy.OAuthHandler(key,secrets)
        auth.set_access_token(tk,tk_secrets)
    
        # Create the API object
        api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)
        return api
    
    if __name__ == '__main__':
        api = authpy('T_API_KEY','T_API_SECRETS','T_ACCESS_KEY','T_ACCESS_SECRET')
    

    Conclusion

    This is it. We have learned how to authenticate to the Twitter API using Tweepy.

    We are now ready to look at some of the basic python functions that you can use to interact with the Twitter API.

    3/5 - (4 votes)