×

Search anything:

Post a tweet with video using Twitter API

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 30 minutes | Coding time: 5 minutes

In this article, we will demonstrate how you can tweet a video along with text and subtitles using the Twitter API using Requests library (native) for HTTP calls like POST and GET. It uses the Media Upload API of Twitter to accomplish this and is similar to the approach of tweeting an image.

The idea is to upload our video to Twitter Server using Media Upload API which will give back an URL pointing to our uploaded video. Following this, we can add more information like meta data and subtitles for the video and continue in the process of making our tweet.

Before we go into the details, we will go through some basic information about Twitter API. You can go directly into the code if you are familiar with the basic details.

Basics of Twitter API

What is an API (Application Program Interface)?

  • An application program interface (API) is a set of routines, protocols, and tools for building software applications. Basically, an API specifies how software components should interact.It is a gateway that lets us access a server's internal functionality, in our case twitter.
  • API is the way for an application to interact with certain system/application/library/etc. For example, there are API's for OS (WinAPI), API's for other applications (like databases) and for specific libraries (for example, image processing), etc. APIs are usually developed in a form consumable by a client application.

api

Steps to perform the task

  1. Register for Twitter API and get your keys
  2. Install dependencies
  3. Write our script

Twitter API

  • The Twitter API is simply a set of URLs that take parameters. They URLs let you access many features of Twitter, such as posting a tweet or finding tweets that contain a word, etc.
  • Twitter allows you to interact with its data tweetsand several attributes about tweets using twitter API.
  • Twitter API's can be accessed only via authenticated requests.

Characteristics of Twitter API

  • The twitter API uses JSON data format for returning and receiving the data.
  • The twitter API is HTTP-based (over SSL) API meaning we can use get method to retrieve data from twitter,post method to send requests to the twitter server and search method to search the twitter posts.
  • The twitter API limits the number of requests that can be sent to the twitter server per access token or twitter account.This is called twitter rate limit.If you encounter twitter rate limit exceeded error it means that Twitter rejected consecutive attempts to access its API under your Twitter account.The rate limit is different for different methods of the API.
  • The methods of twitter API accepts various parameters which are used to cusotmize the requests according to needs.
  • There are twitter API libraries for almost all programming languages.

Read the Documentation of twitter API from here

Getting Twitter API keys

To start with, we will need to have a Twitter developer account and obtain credentials (i.e. API key, API secret, Access token and Access token secret) on the to access the Twitter API, following these steps:

  1. Create a Twitter developer account https://developer.twitter.com/
  2. Go to https://developer.twitter.com/en/apps and log in with your Twitter user account.
  3. Click “Create an app”
  4. Fill out the form, and click “Create”
  5. A pop up window will appear for reviewing Developer Terms. Click the “Create” button again.
  6. In the next page, click on “Keys and Access Tokens” tab, and copy your “API key” and “API secret” from the Consumer API keys section.
  7. Scroll down to Access token & access token secret section and click “Create”. Then copy your “Access token” and “Access token secret.

What is Requests package?

The requests module allows you to send HTTP requests using Python.
The HTTP request returns a Response Object with all the response data (content, encoding, status, etc).We will be using the post method of requests library to send a request to tweet.

requests-1

Install requests package using command:

pip install requests

Media upload request (Twitter Media API)

  • Before we tweet an image using twitter API, We need to upload the media(images, video, Gif, etc) on the twitter server.This is done using media upload request.
  • We will send this request to the twitter server using the requests package of python.Using this method returns a media ID which can be used to uniquely identify the media uploaded on the twitter server.
  • When sending the media upload post request, we can specify various parameters which contain the meta information about the media that we want to post with our tweet like media category, media data and additional owners.

Read more about uploading media from here

Adding meta data

  • We can provide additional information about the media that we are going to upload.This is done by providing an additional parameter in the tweet request.
  • The post request contains the media alt text which provides information(alternate textual description) about the tweet media
  • Now , we can pass the uploaded media id in the post request to add the meta data.

Read more about adding meta data from here

Adding subtitles to video

  • We can provide subtitles to the video we have uploaded on the twitter server.
  • To do this, we have to upload subtitle using the chunked upload endpoint with media category set to subtitles and get the subtitle media_id usinf post request.
  • If the status code of this request is 200 , then it is successful otherwise not
  • Now, we can tweet the video using a post request.

Read more about adding subtitles from here

Python Code And Explanation

After importing the dependencies, first we want to create variables(consumer_key and consumer_secret) that will authenticate with Twitter.You will find all the required variables in your developer's account dashboard and we can copy and paste each of them as strings.

#importing all dependencies
import numpy as np
import tweepy
import requests
import base64

#Define your keys from the developer portal
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXX'
consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

The twitter API requires a single key that is a string of a base64 encoded version of the two keys separated by a colon so we will encode the consumer keys into base64 which is the usable form.

#Reformat the keys and encode them
key_secret = '{}:{}'.format(consumer_key, consumer_secret_key).encode('ascii')
#Transform from bytes to bytes that can be printed
b64_encoded_key = base64.b64encode(key_secret)
#Transform from bytes back into Unicode
b64_encoded_key = b64_encoded_key.decode('ascii')

Now, We will use requests package of python to post an authentication request using twitter authentication resource URL to the twitter server and store the post response in a variable. We To check and make sure that the request worked , We will print the status code of the request response. If the status code printed is 200 then the request worked successfully.

base_url = 'https://api.twitter.com/'
auth_url = '{}oauth2/token'.format(base_url)
auth_headers = {
    'Authorization': 'Basic {}'.format(b64_encoded_key),
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
auth_data = {
    'grant_type': 'client_credentials'
}
auth_resp = requests.post(auth_url, headers=auth_headers, data=auth_data)
print(auth_resp.status_code)
access_token = auth_resp.json()['access_token']

Captureauth-1

Now, we have to upload a video to the twitter server using post request.For this, we will open a video in raw binary format and read it. The resource url for video upload is stored and the parameters for image upload are initialized in form of json.Now we will send a post request with the parameters we initialized.This post request will return a media key which identifies the uploaded video on the twitter server.

file = open('your_video_path', 'rb')
data = file.read()
resource_url='https://upload.twitter.com/1.1/media/upload.json'
upload_video={
    'media':data,
    'media_category':'tweet_video'}
    
video_headers = {
    'Authorization': 'Bearer {}'.format(access_token)    
}

media_id=requests.post(resource_url,headers=video_headers,params=upload_image)

Now , we will assign a meta data to the video we have uploaded on the twitter server. To do this first we will assign all the parameters for the post request in json format and provide a resource URL for creating meta data. Now, we will send a post request to the twitter server and check the status code. If it is 200 then the post request was successful.

tweet_meta={ "media_id": media_id,
  // image alt text metadata
  "alt_text": {
    "text":"your_video_metadata_here" 
  }}
metadata_url = 'https://upload.twitter.com/1.1/media/metadata/create.json'    
metadata_resp = requests.post(metadata_url,params=tweet_meta,headers=auth_data)

metadataresponse

Now we will add subtitles to the video we have uploaded on the twitter server using a post request.

file = open('your_subtitlefile_path', 'rb')
data = file.read()
resource_url='https://upload.twitter.com/1.1/media/subtitles/create.json'
upload_subtitle={
    'media':data,
    'media_category':'Subtitles'
    }
    
subtitle_headers = {
    'Authorization': 'Bearer {}'.format(access_token)    
}

subtitile_id=requests.post(resource_url,headers=subtitle_headers,params=upload_subtitle)

tweet_subtitle={ "media_id": media_id,
  "subtitle_info": {
        "subtitles": [
          "media_id":subtitle_id,
          "language_code":"EN", #The language code should be a BCP47 code (e.g. 'en", "sp"),
          "display_name":"English"
        ]
  }  
  
subtitle_resp = requests.post(subtitle_url,params=tweet_subtitle,headers=auth_data)

Now, we will assign a dictionary variable with the parameter we want to pass into the post request. Here, the status key of dictionary variable is assigned with 'Hello World' which is the message we want to tweet.Also we will specify the media id which we generated to attach the video with our tweet. After this we will assign a variable with the post URL where we will be sending the request to the twitter server.Now use the post method of requests package to send the tweet request and store the response into a variable.

tweet={'status':'hello world','media_ids'=media_id}
post_url = 'https://api.twitter.com/1.1/statuses/update.json'    
post_resp = requests.post(post_url,params=tweet,headers=image_headers)

Capturepost-1

Tweet Posted:

videotweet

Post a tweet with video using Twitter API
Share this