In this tutorial, we will discuss how can we fetch and post tweets on Twitter using twitter API in Python?


  1. A Twitter Account with some tweets posted.
  2. A Twitter developer account

To create a twitter developer account apply here using your Twitter credentials.

Once the account has been created and verified. Create an app by going here.

Twitter developer create app

After providing the required information your new app will be created and now you will be ready to access the API tokens to integrate into your project (in our case is Python script) and fetch tweets using the same.

So select your app and go to the ‘keys and tokens’ section to get you API keys and tokens.

Twitter API tokens

Save all API Keys and tokens to use it in your code.

Now to use these API we need to install the 3rd party library python-twitter. So install it by writing the below command in cmd or terminal.

$ pip install python-twitter

when installed import it using the import twitter into python script and paste your API keys and tokens details into the respective variable of the code given below.

Fetch Tweets using Python

import twitter

#paste your API keys and token here
consumer_key = 'your API Key'
consumer_secret = 'your API secret key'
access_token = 'your ACCESS Token'
access_token_secret = 'your ACCESS Token Secret'

api = twitter.Api(consumer_key=consumer_key,

#fetch all tweets in your timeline and output them.
all_tweets = api.GetHomeTimeline()
print([s.text for s in all_tweets])

#fetch your tweets and output them.
my_tweets = api.GetUserTimeline(api.VerifyCredentials().id)
print([s.text for s in my_tweets])

On carefully implementing the above steps and executing the code, you will be able to see your tweets as output.

Post Tweets using Python

Using the same API object you can post a tweet from your python code without logging into your Twitter account.

tweet = "This is my next Tweet!"

Just call postUpdate() method passing your tweet in string format as a parameter.

Refer python-twitter documentation to know more about the functionality of the API.

If you have any doubts or suggestions then please comment below.

Leave a Reply

four × 2 =