Search anything:

Post a tweet with image 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 an image using the Twitter API using two approaches: Tweepy (simple) and Requests library (native). It uses the Media Upload API of Twitter to accomplish this.

The idea is to upload our image to Twitter Server using Media Upload API which will give back an URL pointing to our uploaded image. Following this, we can add more information like meta data for the image 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.


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.

Approach 1: Tweepy

What is tweepy?

Tweepy is a python dependency that we will be using to generate tweets.Tweepy is a Python library for accessing the Twitter API. It is great for simple automation and creating twitter bots. Tweepy has many features.

Read the Documentation of tweepy from here


Install tweepy using command:

pip install tweepy

Python Code and Explanation

After importing the dependencies, first we want to create 4 variables 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

#variables for accessing twitter API

Now, we'll create a variable called off for auth and use the OAuth handler method of tweepy. This method takes two arguments the consumer key and the consumer secret. This method was written inside of the twepy library and all of its functionality is in our hands.Now we have to call the set access_token method on the auth variable which takes two arguments the access token and the access token secret and that's it we've created our authentication variable now.

#authenticating to access the twitter API

Now that we have our API variable we can perform many different possible tasks.We can make a textual tweet with attached image using update_with_media method which takes image_path and a string as input.

tweet_text=input('enter the tweet ')
image_path =input('enter the path of the image ')

#Generate text tweet with media (image)
status = api.update_with_media(image_path, tweet_text)

Approach 1: Requests library

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.


Install requests package using command:

pip install requests

Media upload request

  • 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 image 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

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

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)
access_token = auth_resp.json()['access_token']


Now, we have to upload an image to the twitter server using post request.For this, we will open an image in raw binary format and read it. The resource url for image 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 image on the twitter server.

file = open('your_image_path', 'rb')
data = file.read()
image_headers = {
    'Authorization': 'Bearer {}'.format(access_token)    


Now , we will assign a meta data to the image 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": {
metadata_url = 'https://upload.twitter.com/1.1/media/metadata/create.json'    
metadata_resp = requests.post(metadata_url,params=tweet_meta,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 image 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)


Tweet Posted


With this, you have the complete knowledge of uploading an image on Twitter server and using it as a tweet. Enjoy.

Post a tweet with image using Twitter API
Share this