Accessing the Twitter API using Twython in Python

From Knowledge Kitchen
Jump to navigation Jump to search


Accessing the Twitter API in Python is easy using any of the available API clients, such as the the Twython library used in these examples.

All users of Twitter's API must be authenticated using OAuth, a common system of authentication used by many popular APIs such as Google, Twitter, and Facebook.

Understanding OAuth

Twitter's API, like many others, uses the OAuth standard to grant developers the ability to access the data.

Install Twython

Run the following from the command line:

pip install Twython

Set up your Twitter Application

  1. Go to https://dev.twitter.com/ and sign up
  2. Click on “My apps”, fill in the information
    • the “website” field can be anything
    • If you don’t have a web site, feel free to write any random website url (github.com, etc)
  3. Submit the app info, and create a token
    • write down the Consumer (API) key & secret, Access token & secret token. (you'll need to plug these into your code later)
  4. If you would like to access your own Twitter account through the API, you may need to use your randomly generated user id number, which can be easily found.

Post a status update

 1 from twython import Twython
 2 
 3 # Twitter application authentication
 4 # You get these credentials by registering your app with Twitter
 5 #CONSUMER API KEY & SECRET
 6 API_KEY = 'your_api_key'
 7 API_SECRET = 'your_api_secret'
 8 #ACCESS TOKEN & SECRET
 9 OAUTH_TOKEN = 'your_token'
10 OAUTH_TOKEN_SECRET = 'your_token_secret'
11 
12 # connect to the TWitter API using your app's credentials
13 api = Twython(API_KEY,API_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
14 
15 api.update_status(status= "#KnowledgeKitchen I <3 Database Design!")

Search by keyword

 1 from twython import Twython, TwythonError
 2 
 3 # Twitter application authentication
 4 # You get these credentials by registering your app with Twitter
 5 #CONSUMER API KEY & SECRET
 6 API_KEY = 'your_api_key'
 7 API_SECRET = 'your_api_secret'
 8 #ACCESS TOKEN & SECRET
 9 OAUTH_TOKEN = 'your_token'
10 OAUTH_TOKEN_SECRET = 'your_token_secret'
11 
12 # connect to the TWitter API using your app's credentials
13 api = Twython(API_KEY,API_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)
14 
15 try:
16     search_results = api.search(q='#KnowledgeKitchen', count=50)
17     
18     for post in search_results['statuses']:
19         #each post is a dictionary
20     
21         #print out a select few values from the dicitonary of this post
22         print('Tweet from {user} on date: {date}:\n{text}'.format(
23             user = post['user']['screen_name'], 
24             date = post['created_at'],
25             text = post['text']
26         ))
27 except TwythonError:
28     print('Unable to connect to the Twitter API')


What links here