Python Friday #111: Twitter Authentication & Tweepy

When you explore the Twitter API, you will get a lot of 401 errors. Let’s look how we need to set the permissions for our App so that we can explore the Twitter API without interruptions.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Environment specific permissions for your application

In a project, each environment gets its own app, and this allows us to give the development app different access rights than our production app. I strongly recommend that you give your development app all possible permissions – so you can explore the Twitter API without restrictions.

However, a long list of permissions will make your users suspicious – and rightfully so. For stage and production, you should only request permissions that your app absolutely must have. This is good practice and massively reduces the risk to your users.

Twitter gives us in the free plan 3 environments. Let us use them effectively.

 

V1 and V2 endpoints

Twitter is currently moving between two major versions of their API endpoints. During this transition, you need both endpoints, and with that, you need to set permissions for V1 and V2.

Make sure that you expand the V1 and the V2 endpoints in the permission settings of the Twitter Developer portal and select the access rights in both places. This may change in the future, but until then add everything you find.

 

Capturing the authentication token

Tweepy does a good job of hiding the details of the OAuth protocol. Behind the scenes, Tweepy gets a user-specific key and a secret to communicate with Twitter on behalf of the user. If we don’t capture these tokens, we’ll have to authorize our application every time we want to call the Twitter API.

With this code sample we can repeat the PIN based authorisation and print out the user specific tokens:

Run the script, take those tokens and put them into the .env file. We can now use this sample code to reuse the user tokens and talk to the Twitter API without another authorisation:

YYou can come back tomorrow, run this second script again and it will tweet without asking for authentication. This will work as long as the user does not revoke the permissions of your App or your App needs additional rights.

 

Next

Capturing the user access tokens using the example above works, but with your production application you need something more user-friendly. Next week we look how you can obtain the tokens with a Flask app.

4 thoughts on “Python Friday #111: Twitter Authentication & Tweepy”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.