Access the Twitter API in Python

Access to the Twitter API from Python. Supports both Python 2 and 3.

There is also python-twitter, but basically you just send an HTTP Request and get JSON, so use the Twitter-only library. I thought it wasn't there, so I wrote it myself. Only OAuth authentication uses a separate library.

OAuth library

You need ** OAuth authentication ** to access Twitter. The authentication method is so complicated that ordinary people use libraries.

This time, I will use Requests-OAuthlib, which is self-identified as "OAuth for humans". I don't know what kind of creatures other libraries envision.

Application registration

To access the Twitter API, you first need to register your application. When you finish this

Two keys are issued. In addition, for each user of the app

Two keys are issued. You need these four keys to access the Twitter API.

How to get it is [Konohen](http://website-planner.com/twitter%E3%82%A2%E3%83%97%E3%83%AA%E3%82%B1%E3%83%BC % E3% 82% B7% E3% 83% A7% E3% 83% B3% E3% 81% AE% E4% BD% 9C% E6% 88% 90% EF% BC% 88consumer-key% E3% 80% 81consumer -see secret% E3% 80% 81access-token% E3% 80% 81access-token-secret /).

The application registration itself is free, but it seems that it became necessary to register the mobile number from around February 2014. I don't know the details, so ggr.

Post a tweet

Once you get the key, write the code right away. Below, replace the CK, CS, AT, AS parts with your own key as appropriate.

tweet.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from requests_oauthlib import OAuth1Session

CK = 'XXXXXXXXXXXXXXXXXXXXXX'                             # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Accesss Token Secert

#URL for posting tweets
url = "https://api.twitter.com/1.1/statuses/update.json"

#Tweet body
params = {"status": "Hello, World!"}

#Post by POST method with OAuth authentication
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.post(url, params = params)

#Check the response
if req.status_code == 200:
	print ("OK")
else:
	print ("Error: %d" % req.status_code)

The basics are like this. If you want to add an image, rewrite the posted part like this.

tweet_with_image.py


#Tweet body
files = {
	"status": "Hello, World!",
	"media[]": open("image.png ", "rb")
}

#Post by POST method with OAuth authentication
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.post(url, files = files)

** * Added on 2015/04/27 ** It seems that the specifications for posting images have changed. See here → Tweet with image in Python

Get the timeline

There is no big difference except that the URL changes and POST becomes GET. The return value is JSON, and 20 tweets are in list format. Here, only the text is displayed, but it also includes a lot of meta information such as user information, tweet time, and number of favs.

timeline.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from requests_oauthlib import OAuth1Session
import json

CK = 'XXXXXXXXXXXXXXXXXXXXXX'                             # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'         # Accesss Token Secert

#URL for getting the timeline
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"

#There are no particular parameters
params = {}

#GET with OAuth
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.get(url, params = params)

if req.status_code == 200:
	#Since the response is in JSON format, parse it
	timeline = json.loads(req.text)
	#Display the body of each tweet
	for tweet in timeline:
		print(tweet["text"])

else:
	#In case of error
	print ("Error: %d" % req.status_code)

There is no need for parameters, but you can set the range of tweet IDs to be acquired (assigned in chronological order) and the number of tweets (standard 20, maximum 200).

Other APIs

After that, you can do almost anything by rewriting the URL and params. Click here for a list of APIs provided. (English) https://dev.twitter.com/docs/api/1.1

The "unfollow" API is friendships / destroy, which I've seen many times.

Notorious API restrictions

Twitter has a generous API, so it can be functionally almost the same as the official client. However, there is a limit to the number of requests. In particular, Home Timeline is so strict that ** up to 15 times in 15 minutes **, so it is not possible to update the timeline every few seconds.

The remaining API number and the time of the next update are stored in the request header.

#GET with OAuth
twitter = OAuth1Session(CK, CS, AT, AS)
req = twitter.get(url, params = params)

if req.status_code == 200:

	#API rest
	limit = req.headers['x-rate-limit-remaining']
	#API limit update time(UNIX time)
	reset = req.headers['x-rate-limit-reset']

	print ("API remain: " + limit)
	print ("API reset: " + reset)

As a way to overcome API restrictions

There is such a thing.

What can i do after this

The possibilities are endless.

Recommended Posts

Access the Twitter API in Python
Tweet using the Twitter API in Python
Getting the arXiv API in Python
Hit the Sesami API in Python
Hit the web API in Python
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Try hitting the YouTube API in Python
Evernote API in Python
C API in Python 3
Try using the BitFlyer Ligntning API in Python
Tips for hitting the ATND API in Python
Hit the Firebase Dynamic Links API in Python
Try using the DropBox Core API in Python
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Download the file in Python
Find the difference in Python
Try using the Twitter API
Try using the Twitter API
Blender Python API in Houdini (Python 3)
Call the API with python3.
Crawl the URL contained in the twitter tweet with python
Using the National Diet Library Search API in Python
Try hitting the Twitter API quickly and easily with Python
Get your heart rate from the fitbit API in Python!
Python in the browser: Brython's recommendation
Save the binary file in Python
Specifying the date with the Twitter API
[Python] Hit the Google Translation API
Get the desktop path in Python
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
Try PLC register access in Python
Hit the Etherpad-lite API with Python
Create Gmail in Python without API
Use the Flickr API from Python
[LINE Messaging API] Issue channel access token v2.1 in Python
I wrote the queue in Python
Calculate the previous month in Python
Examine the object's class in python
Get the desktop path in Python
Quickly implement REST API in Python
The first step in Python Matplotlib
I wrote the stack in Python
Master the weakref module in Python
An easy way to hit the Amazon Product API in Python
Export the contents acquired by Twitter Streaming API in JSON format
Hit the New Relic API in Python to get the server status
A class that summarizes frequently used methods in twitter api (python)
Regularly upload files to Google Drive using the Google Drive API in Python
Play by hitting the Riot Games API in Python First half
Collecting information from Twitter with Python (Twitter API)
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Access the Docker Remote API with Requests
Mouse operation using Windows API in Python
Load the remote Python SDK in IntelliJ
Check the behavior of destructor in Python
How to access environment variables in Python
Learn the design pattern "Flyweight" in Python