Twitter API V2: For Programming

Twitter API V2: For Programming

This tutorial is mainly based on programming using Twitter API V2 and Tweepy Python Libraries. The V2 might be a good upgrade for your if you have been programming with Twitter for a while. Twitter suggests that apps move to V2 and new apps to use V2 right from the start.

Twitter API V2: For Programming
Source: Laura O’Mahony
Programming with Twitter API V2

I will not focus on similarities and differences, but I will cover how to start using the V2. Compared with hacking on the Twitter API directly, using the tweepy libraries simplify the Twitter API and reduces the amount of code you need to manage.

YouTube Tutorials on Twitter API V2

Python and Twitter API V2 for Programming

For further information, you can watch our 3 video tutorial series. Use the timestamps provided to watch the part that covers the following:

  • Creating a Twitter developer account
  • Use Postman to test the Twitter API
  • Use the API to follow other people on Twitter
  • Conduct a search for tweets with certain keywords
  • Get and view the tweet URL on Twitter
  • Use API to retweet
  • Use Flask to build a Lead Generation App to browse for tweets, retweet or respond directly on Twitter

Retrieving API Keys

We will not discuss this in great detail, just visit the Twitter Developer Portal and create a developer account with developer keys. It is an uncomplicated process, they will just ask you the main purpose, you have to answer honestly and copy the keys to proceed with the rest of the steps. For more information, visit Twitter Docs

Postman on the Twitter V2 API

By far this is the most simplest way to test the API. Twitter offered a Postman collection with all the necessary access routes for the API. Your role is to just install the collection in your Postman and start working.

Download Postman: https://www.postman.com/downloads/

Install the Twitter Postman Collection: https://www/postman.com/twitter/workspace/collection/9956214-784efcda-ed4c-4491-a4c0-a26470a67400?ctx=documentation

They have a code snippet on their website, however Tweepy is straightforward, easy to implement and use.

Tweepy for V2 Twitter API

Find the Tweepy documentation on this link: https://docs.tweepy.org/en/stable/client.html

The main difference between the other versions and v2 is the authentication. In place of creating the API, you se this code to create the client:

client = tweepy.Client(bearer_token='enter-token', 
                       consumer_key='enter-consumer-key', 
                       consumer_secret='enter-consumer-secret', 
                       access_token='enter-access-token', 
                       access_token_secret='enter-secret')

The client will let you call the functions that you need for posting, searching or following people. For example, to follow a user you execute this:

client.follow_user(userId)

And get the userId from this function:

client.get_user(username)

Using Tweepy is as simple as ABC. Find the source code for this tutorial on GitHub: GitHub-skolo-online/twitter-v2-api

A search Function to Search using certain Keywords

import tweepy
import config
import json
def getClient():
    client = tweepy.Client(bearer_token=config.BEARER_TOKEN,
                           consumer_key=config.API_KEY,
                           consumer_secret=config.API_KEY_SECRET,
                           access_token=config.ACCESS_TOKEN,
                           access_token_secret=config.ACCESS_TOKEN_SECRET)
    return client
def searchTweets(client, query, max_results):
tweets = client.search_recent_tweets(query=query, max_results=max_results)
tweet_data =  tweets.data
    results = []
if not tweet_data is None and len(tweet_data) > 0:
        for tweet in tweet_data:
            obj = {}
            obj['id'] = tweet.id
            obj['text'] = tweet.text
            results.append(obj)
return results
def getTweet(client, id):
    tweet = client.get_tweet(id, expansions=['author_id'], user_fields=['username'])
    return tweet
def returnSearchTweetList(query, max_results):
    client = getClient()
    tweets = searchTweets(client, query, max_results)
objs = []
if len(tweets) > 0:
        for tweet in tweets:
            twt = getTweet(client, tweet['id'])
            obj = {}
            obj['text'] = tweet['text']
            obj['username'] = twt.includes['users'][0].username
            obj['id'] = tweet['id']
            obj['url'] = 'https://twitter.com/{}/status/{}'.format(twt.includes['users'][0].username, tweet['id'])
            objs.append(obj)
return objs
def retweet(id):
    client = getClient()
    client.retweet(id)

NB* create a config file and save the API keys on it or save these API keys in the environment to retrieve them in the getClient function.

 The code is responsible for the following:

  1. Getting a maximum of 10 tweets based on the keywords you specified.
  2. Draw out the tweet-id and tweet-text
  3. Calling the API once more to show the author of the tweet
  4. Building a URL – use it later on to find the tweet on Twitter
  5. Easy retweet function

Setting Up Python Flask App

We created a flask app that we will use to enter the search query and see the tweets displayed back to us, this allows us to either: (a) view the tweet on Twitter to interact with it or (b) retweet the tweet from the flask application.

The app.py file will be like:

from flask import Flask, render_template, url_for, redirect, request
import config
import search

def page_not_found(e):
  return render_template('404.html'), 404

app = Flask(__name__)
app.config.from_object(config.config['development'])

app.register_error_handler(404, page_not_found)

@app.route('/', methods=["GET", "POST"])
def index():

query = 'Project Management lang:en -is:retweet'

if request.method == 'POST':
        query = '{} lang:en -is:retweet'.format(request.form['query'])

max_results = 10
    tweets = search.returnSearchTweetList(query, max_results)

return render_template('index.html', **locals())

@app.route('/retweet/<string:tweetId>/', methods=["GET", "POST"])
def reweet(tweetId):
    search.retweet(tweetId)

return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000', debug=True)

The html template will be like:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<title>Skolo</title>
    <link rel="shortcut icon" type="image/x-icon" href="{{ url_for('static', filename='images/favicon.png') }}">
<!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
  <body>
<div class="container mt-5 mb-5">
<h1 class="mb-3">Your Latest Tweets</h1>
<form class="" action="/" method="post">
<div class="mb-3">
          <label for="query" class="form-label">Enter the Search Query for Twitter</label>
          <input type="text" class="form-control" id="query" name="query" placeholder="Search for .......">
        </div>
<button type="submit" class="btn btn-primary"> RUN SEARCH QUERY </button>
      </form>
<div class="card-group mt-5">
<div class="row">
{% for tweet in tweets %}
          <!-- Card starts here -->
          <div class="col-lg-4 mb-3">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title">Username: {{tweet.username}}</h5>
                <p class="card-text">{{tweet.text}}</p>
              </div>
              <div class="card-footer">
               <div class="row">
                 <div class="col-lg-6">
                   <a href="{{tweet.url}}"><button class="btn btn-primary btn-block">VIEW TWEET</button></a>
                 </div>
                 <div class="col-lg-6">
                   <a href="/retweet/{{tweet.id}}/"><button class="btn btn-success btn-block">RETWEET</button></a>
                 </div>
               </div>
              </div>
            </div>
          </div>
          <!-- Card ends here -->
          {% endfor %}
</div>
</div>
</div>
<!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

The final result:

Browsing tweets using certain keywords

Use Case:

Build the app to be like a lead generation tool, use it for finding out when certain keywords are in use, responding immediately in tweets or retweeting. Keep in mind that you can also use automation to the code to retweet or respond immediately.

Thank You

We would like to thank you for your time, feel free to leave a comment on the YouTube video comment section. Tati Digital

Leave a Reply

Your email address will not be published.

Subscribe to our mailing list

And get this 💃💃 Free😀 eBook !

Holler Box