How to build Twitter Auth API with Flask and Tweepy

Kwesi Dadson
6 min readMay 29, 2022

--

I’ve wanted to put this together for a long time; it’s here now!

What are we building exactly?

If you’ve ever worked with tweepy or Twitter api itself, you’d probably understand what we’re trying to do. Twitter allows you to do actions you’d usually do on twitter as a user, via API. This means you can create a script that can tweet something at regular intervals, build bots that respond to mentions, build bots that monitor keywords and a whole lot.

You’d need API keys for your account to do this. After you’ve done this for a while, you’d get bored and want to allow your friends try this cool stuff too. Now, remember your friends no nothing about programming and they definitely would have a hard time generating Twitter API keys (It’s annoying!).

Here’s the solution: We’re building an API that allows users to authorize their twitter accounts so you can control it with your API keys!

Here’s a diagram attempting to explain the process:

Process flow

Flask API: It’s alive!

I’m not going to spend much time here since this is out of scope. Checkout flask if you’re new to it! Let’s start with this code and make sure our API works fine. Create a project folder twitter_auth_api and create your first file app.py. Paste the code below and make sure it works fine:

from flask import Flaskapp = Flask(__name__)@app.route('/')
def home():
return "API is Alive and Well!"
if __name__ == '__main__':
app.secret_key = "AUTH_KWESI_SECRET"
app.run()

I usually keep a requirements.txt with a list of modules I need. Put flask, tweepy and flask_corsin there. Your folder structure should look like this:

twitter_auth_api
> app.py
> requirements.txt

#requirements.txt content
flask
tweepy
flask_cors

Tweepie π

Time to test out Tweepy. Our goal here is to be able to post an update on Twitter from our script. Let’s get started!

This is what the code for that looks like:

You have so many questions at this point, I know. First things first. Let’s get those four authentication variables. Here’s how: Twitter API. Remember when I said it’s annoying? Yeah! Let me know when you finally have those tokens!

Make sure your Twitter app has write access!

Frontend

We’ll need a frontend to test out this API properly. Let’s build a simple React project for this.

If you’ve never created a react project, you may have to install a few tools. Checkout the official docs for react

Create a new React project

npx create-react-app twitter-auth-web

What we want to do is put a twitter login button on the index page, when you click that it should take you to our api for authorization. You’ll then be redirected back to the web app with a verification token, which will be sent to the api again to generate the actual tokens.

A project has been generated for you. Open it in VS code (or any editor/IDE) and let’s finish this quickly.

The button

Replace the code in App.js with this:

You can run the app. Open your terminal within the project folder and run it with the command npm start

Connecting the first wire

We want the button to trigger the first step in the authorization process. Let’s do this!

Let’s build the authorization endpoint!

On line 9, 10 and 13, we handle cross-origin issues since we’ll be accessing the API from a different “domain”.

Here’s what we’re doing:

Providing a callback url that twitter will redirect to when it’s time to send back our expected token. The reason we provide a callback url is that, twitter allows us to set up multiple callback urls on their end. Set up your react app’s callback url on twitter as:

http://localhost:3000/twitter_auth_callback

We then generate the actual twitter auth url which we want to redirect to. This is sent back to the frontend so you can redirect to it. Note the two different redirect urls here: 1. The one our app should redirect to, that is twitter auth’s url. 2. The one twitter should redirect to after it’s done. That is our specified callback url — within our app.

Go to https://developer.twitter.com/en/portal/dashboard, select the app you created and add the callback url specified above.

Note: Twitter has made some changes to their developer portal. Go to the user authentication settings section on the app details page, click edit and update your settings accordingly:

App details page

Calling the first endpoint

Let’s work on the frontend a bit. All we’ll do is call the endpoint and pass a JSON containing the callback url.

In the terminal of your frontend app (within the project folder), run npm install axios

That’s the module for making API requests. This is what your code should look like:

Check your browser console for the response. You should see something like this:

{message: 'success', 
redirect_url: 'https://api.twitter.com/oauth/authorize?oauth_token=hdDF6gAAAAAA2eLeAAABgOV64r4'}

Redirecting to Twitter

Before we call the redirect url we got from the API, let’s build our callback endpoint on the frontend so Twitter can get back to us after we send them the request. We’ll make use of react-router here.

Install dependencies and update your react code:

npm install react-router-dom@6

Update your index.js to look like this:

Note the new lines.

Nothing has changed so far, but this allows us to create a new endpoint for our callback. Go on and create a new file next to App.js and name it TwitterCallback.js

Create an onClick function for the button we created in App.js . Update your code to be this:

Now when you run both the frontend and backend apps, you should be able to click on the button and get redirected to twitter’s auth page.

Twitter redirecting to us

Time to build that callback endpoint on the frontend and also on the backend. Once twitter redirects to our callback url, it should go to that endpoint, then that endpoint will pick up the params from twitter and forward it to our backend to finally generate the tokens for us.

Here’s what the frontend code will look like:

Index.js

Changing the strict mode tag fixed a bug I had during development. Somehow <React.StrictMode> causes useEffect() to run twice every time!

TwitterCallback.js

The callback page will make more sense once we build the backend endpoint and test the whole flow out. Here’s the backend endpoint, add it to app.py:

Test run

You have all the code you need to make this work now. Time to check it out and see what each part does.

Click on the button, that should take you to twitter’s auth page. Authorize our app, twitter redirects you to our callback endpoint which then picks up the parameters sent by twitter (check the address bar) and forwards it to the /api/twitter_auth_callback endpoint to generate the necessary tokens we need to access the user’s information.

Conclusion

This is just the beginning. Once you have the tokens, there are endless possibilities. I know you know this and that’s probably why you’re interested in being able to generate tokens for other users.

If you’re confused about how to use the tokens, check how we used it in twitter_script.py . You just have to replace the access_token and access_secret with what was given you for the authorizing user.

Have fun implementing all those ideas!

Repositories:

API, Web

--

--