How to Connect to Twitter With Python

Editor's note: This tutorial was originally written in 2014 using Python 2 and Twitter's v1.1 API. Twitter is now X, and API access has changed significantly — most endpoints now require a paid plan and the X API v2. The examples below have been updated to Python 3 syntax, but check the X developer documentation and tweepy documentation for current requirements.

Several third-party Python packages wrap Twitter's API. This guide looks at two: tweepy and twitter. Tweepy has more extensive documentation; the twitter package has concise examples.

Getting Started

To use the API, create an app in the X developer portal, then generate your API keys and access tokens.

Neither package comes with Python, so install them with pip:

pip install tweepy
pip install twitter

Posting a Status Update

With tweepy (v1.1-style API):

import tweepy

auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(token, token_secret)
client = tweepy.API(auth)
client.update_status("#Python Rocks!")

You create an OAuth handler with your keys, set the access tokens, create an API object, and post the update.

With the twitter package:

import twitter

auth = twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)
client.statuses.update(status="#Python Rocks!")

The twitter package's OAuth setup is arguably cleaner.

In current versions of tweepy, posting uses the v2 API through tweepy.Client:

client = tweepy.Client(consumer_key=key, consumer_secret=secret,
                       access_token=token, access_token_secret=token_secret)
client.create_tweet(text="#Python Rocks!")

Getting Timelines

With tweepy:

timeline = client.home_timeline()
for item in timeline:
    print(f"{item.user.screen_name} says '{item.text}'")

With the twitter package, results come back as a list of dictionaries:

timeline = client.statuses.home_timeline()
for item in timeline:
    print(f"{item['user']['screen_name']} says '{item['text']}'")

To get another user's timeline with the twitter package:

user_timeline = client.statuses.user_timeline(screen_name="someuser")

Getting Friends and Followers

Tweepy can list the accounts you follow and your followers. By default, these calls return a limited number of results; to get all of them, use a cursor:

for friend in tweepy.Cursor(client.get_friends).items(200):
    print(friend.name)

for page in tweepy.Cursor(client.get_followers).pages():
    for follower in page:
        print(follower.name)

Use .items(n) to fetch a set number of results or .pages() to iterate over everything.

Wrapping Up

These packages offer much more than this guide covers. Tweepy is generally more intuitive and better documented, and it supports the current X API v2.

Further Reading

Need help with an API integration or automation project? I.T. For Less can help — contact us.

Strategy & Consulting