Internship at OpenGenus

Become this book -> Problems on Array: For Interviews and Competitive Programming

Reading time: 30 minutes | Coding time: 5 minutes

In this commodity, nosotros will demonstrate how you tin tweet an prototype using the Twitter API using two approaches: Tweepy (unproblematic) and Requests library (native). It uses the Media Upload API of Twitter to attain this.

The thought is to upload our image to Twitter Server using Media Upload API which will requite dorsum an URL pointing to our uploaded prototype. Following this, we can add more information like meta data for the image and continue in the process of making our tweet.

Earlier nosotros go into the details, we will go through some basic information near Twitter API. You can go directly into the code if you lot are familiar with the bones details.

Basics of Twitter API

What is an API (Awarding Program Interface)?

  • An awarding programme interface (API) is a gear up of routines, protocols, and tools for edifice software applications. Basically, an API specifies how software components should interact.Information technology is a gateway that lets the states access a server'south internal functionality, in our example twitter.
  • API is the style for an application to interact with sure 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, prototype processing), etc. APIs are usually developed in a form consumable by a customer 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 just a set of URLs that take parameters. They URLs let you admission many features of Twitter, such every bit posting a tweet or finding tweets that contain a word, etc.
  • Twitter allows you to collaborate with its information tweetsand several attributes about tweets using twitter API.
  • Twitter API'southward can be accessed just 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,mail 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 tin can exist sent to the twitter server per access token or twitter business relationship.This is called twitter rate limit.If you encounter twitter rate limit exceeded mistake it means that Twitter rejected consecutive attempts to admission its API under your Twitter business relationship.The charge per unit limit is different for different methods of the API.
  • The methods of twitter API accepts various parameters which are used to cusotmize the requests co-ordinate to needs.
  • There are twitter API libraries for almost all programming languages.

Read the Documentation of twitter API from hither

Getting Twitter API keys

To start with, we will need to have a Twitter developer account and obtain credentials (i.due east. API fundamental, API underground, Admission token and Access token underground) on the to admission the Twitter API, post-obit these steps:

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

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 neat for simple automation and creating twitter bots. Tweepy has many features.

Read the Documentation of tweepy from hither

tweepytwitter-1

Install tweepy using command:

            pip install tweepy                      

Python Code and Explanation

After importing the dependencies, showtime we want to create 4 variables that will authenticate with Twitter.You will find all the required variables in your developer'southward account dashboard and we tin can copy and paste each of them as strings.

            #importing all dependencies import numpy as np import tweepy  #variables for accessing twitter API consumer_key='XXXXXXXXXXXXXXXXXXXXXXXXXX' consumer_secret_key='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' access_token='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' access_token_secret='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'                      

Now, we'll create a variable called off for auth and apply 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.At present we have to call the gear up access_token method on the auth variable which takes two arguments the admission token and the access token hugger-mugger and that's it we've created our authentication variable now.

            #authenticating to access the twitter API auth=tweepy.OAuthHandler(consumer_key,consumer_secret_key) auth.set_access_token(access_token,access_token_secret) api=tweepy.API(auth)                      

At present that nosotros have our API variable we can perform many different possible tasks.We can make a textual tweet with attached epitome using update_with_media method which takes image_path and a string every bit input.

            tweet_text=input('enter the tweet ') image_path =input('enter the path of the image ')  #Generate text tweet with media (prototype) status = api.update_with_media(image_path, tweet_text) api.update_status(condition=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 information (content, encoding, condition, etc).We will be using the mail service method of requests library to ship a request to tweet.

requests-1

Install requests package using control:

            pip install requests                      
  • Earlier we tweet an epitome using twitter API, Nosotros need to upload the media (images,video,Gif,etc) on the twitter server. This is done using media upload request.
  • We will send this asking to the twitter server using the requests package of python.Using this method returns a media ID which can exist used to uniquely identify the media uploaded on the twitter server.
  • When sending the media upload post request, nosotros can specify diverse parameters which contain the meta data 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

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

Read more about adding meta data from here

Python Lawmaking And Explanation

Later on importing the dependencies, first we desire to create variables(consumer_key and consumer_secret) that will authenticate with Twitter.You will discover all the required variables in your developer'due south business relationship 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 cord of a base64 encoded version of the 2 keys separated by a colon so nosotros will encode the consumer keys into base64 which is the usable course.

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

At present, We will employ requests package of python to mail an authentication asking using twitter authentication resource URL to the twitter server and shop the mail response in a variable. We To check and make certain that the request worked , We will print the condition code of the request response. If the condition code printed is 200 then the request worked successfully.

            base_url = 'https://api.twitter.com/' auth_url = '{}oauth2/token'.format(base_url) auth_headers = {     'Dominance': 'Basic {}'.format(b64_encoded_key),     'Content-Type': 'application/ten-www-grade-urlencoded;charset=UTF-8' } auth_data = {     'grant_type': 'client_credentials' } auth_resp = requests.mail service(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 an prototype to the twitter server using post request.For this, we will open an image in raw binary format and read information technology. The resources url for image upload is stored and the parameters for image upload are initialized in class of json.At present we will ship a postal service request with the parameters nosotros initialized.This post request will render a media key which identifies the uploaded image on the twitter server.

            file = open('your_image_path', 'rb') data = file.read() resource_url='https://upload.twitter.com/1.i/media/upload.json' upload_image={     'media':data,     'media_category':'tweet_image'}      image_headers = {     'Potency': 'Bearer {}'.format(access_token)     }  media_id=requests.mail(resource_url,headers=image_headers,params=upload_image)                      

Now , we will assign a meta data to the paradigm we take uploaded on the twitter server. To do this outset nosotros will assign all the parameters for the post asking in json format and provide a resources URL for creating meta data. At present, we will send a post request to the twitter server and check the status code. If it is 200 so the mail service request was successful.

            tweet_meta={ "media_id": media_id,   // epitome alt text metadata   "alt_text": {     "text":"Donuts"    }} 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 assign a lexicon variable with the parameter we desire to pass into the mail service request. Here, the status primal of dictionary variable is assigned with 'Hello World' which is the message we want to tweet.Also nosotros volition specify the media id which we generated to attach the image with our tweet. Afterward this we will assign a variable with the post URL where we will be sending the request to the twitter server.Now employ the post method of requests package to transport the tweet asking and store the response into a variable.

            tweet={'status':'hullo globe','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

imagetweet

With this, y'all have the complete noesis of uploading an paradigm on Twitter server and using it as a tweet. Bask.