After deciding that I’d like to automate a weekly tweet of one of my existing blog post, to keep you entertained a bit more now that my posting frequency has diminished lately, I started by googling the different tools and platforms that can be used to do that. However, I quickly realized that it would be more fun to use the Twitter API to automate these tweets myself.
If you need to use the Twitter API for something important, or at least for more than just sending the occasional tweet, I’d still advise you to use one of the many tools and libraries that are available. Specifically for Python, Tweepy seems a good candidate. Also know that there are options for which programming is not required. But we wouldn’t be nerds if we’d use those, now would we?
Anyway, in this article I’ll go for a more bare-bones approach that uses the Twitter API from a relatively low level.
The Twitter API
The first step is to use an existing Twitter account to get access to the Twitter API. Everything you need to know to do that is described clearly on the Twitter website. The free Essential access is sufficient for a basic application that tweets now and then. You’ll need to figure out how to set it up and how to generate the four keys that you’ll need in the Python code that follows. You can do that from your Twitter Developer Portal. You’ll need the following keys.
- API Key (
API_KEY
) - API Key Secret (
API_KEY_SECRET
) - Access Token (
ACCESS_TOKEN
) - Access Token Secret (
ACCESS_TOKEN_SECRET
)
The names in the MONOSPACE
font in brackets are the names of the environment variables that the Python code expects you to put your keys in before running it.
Authentication
After getting access, the first thing to do to actually use the Twitter API is authenticate. Say that you wish to access my recent tweet on Cherenkov radiation through the API. The id of that tweet is 1467485996954664967, and you can access it directly through the URL
https://twitter.com/tomroelandts/status/1467485996954664967.
This link can be accessed by anyone, including people without a Twitter account. To access this tweet through the API, you would need to use the so-called endpoint “GET /2/tweets
”. The endpoint URL for the tweet is therefore
https://api.twitter.com/2/tweets/1467485996954664967.
However, if you try to follow that link, you’ll see that it will complain with the error Unsupported Authentication. That is because you need to authenticate first. The authentication protocol to use for the Twitter API is OAuth (Open Authorization). What OAuth does, is allow you to have your application access Twitter on your behalf without having to give it your actual Twitter username and password. OAuth is also used by Google, Facebook, and others.
If an application only needs access to public information, e.g., to access the mentioned tweet, authentication can be done using a so-called bearer token, which you can also generate from your Twitter Developer Portal. A bearer token is used to authenticate your app to the API, but without allowing it to do stuff as if it were you. But because I’m trying to create a new tweet, a bearer token is not sufficient, and I won’t go into that method further.
Create a Tweet
OAuth is not necessarily an easy thing to implement. However, luckily for us, there is a Python library called requests_oauthlib
that provides an easy way to access web APIs using OAuth, based on the underlying libraries requests
, which implements HTTP requests, and oauthlib
, which implements OAuth itself.
Because requests_oauthlib
does all the work, the resulting Python program is short. The following script posts the tweet “Hello, World!”.
# Python 3 code. from requests_oauthlib import OAuth1Session from os import environ api_key = environ['API_KEY'] api_key_secret = environ['API_KEY_SECRET'] access_token = environ['ACCESS_TOKEN'] access_token_secret = environ['ACCESS_TOKEN_SECRET'] url = '<a href="https://api.twitter.com/2/tweets' payload">https://api.twitter.com/2/tweets' payload</a> = {'text': 'Hello, World!'} oauth = OAuth1Session(api_key, client_secret=api_key_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) response = oauth.post(url, json=payload) if response.status_code == 201: print(response.json())
You can also use this approach to retrieve a tweet (even though using a bearer token would also be sufficient). To do that, only a few lines need to be changed, as follows.
# Python 3 code. from requests_oauthlib import OAuth1Session from os import environ api_key = environ['API_KEY'] api_key_secret = environ['API_KEY_SECRET'] access_token = environ['ACCESS_TOKEN'] access_token_secret = environ['ACCESS_TOKEN_SECRET'] tweet_id = 1467485996954664967 url = '<a href="https://api.twitter.com/2/tweets/">https://api.twitter.com/2/tweets/</a>{}'.format(tweet_id) oauth = OAuth1Session(api_key, client_secret=api_key_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) response = oauth.get(url) if response.status_code == 200: print(response.json())
Happy (automated) tweeting!
Add new comment