アプリケーション登録
1.こちらにアクセスし、「Create New App」を選択
2.必要事項を入力し、「Create your Twitter application」を選択
Access Token取得
1.先の操作後の画面で「Keys and Access Tokens」タブを選択
2.「Create my access token」(画面最下部)を選択
3.同じ最下部あたりに情報が出力される。
Pythonでちょっとテスト
環境
python関連のパッケージ。インストール方法等は他サイトを参考にしてください。
- python 2.7.9
- pip 1.3.1
※ python 2.7.6では、REST APIとの通信の際に以下のようなエラーが出た。
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:79:
InsecurePlatformWarning: A true SSLContext object is not available.
This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail.
For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
上記サイトの説明を読むと、2.7.9へのアップグレードを推奨すると。ということで、2.7.9へアップグレードしました。
OAuthの認証ライブラリをインストール
$ pip install requests requests_oauthlib
テストコード
ソースコード
twitter_api_test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from requests_oauthlib import OAuth1Session
oauth_info = {
'consumer_key': os.environ.get('TWITTER_API_CONSUMER_KEY'),
'consumer_secret': os.environ.get('TWITTER_API_CONSUMER_SECRET'),
'access_token': os.environ.get('TWITTER_API_ACCESS_TOKEN'),
'access_token_secret': os.environ.get('TWITTER_API_ACCESS_TOKEN_SECRET')
}
oauth = OAuth1Session(
oauth_info['consumer_key'],
oauth_info['consumer_secret'],
oauth_info['access_token'],
oauth_info['access_token_secret']
)
url = 'https://api.twitter.com/1.1/search/tweets.json'
params = {
'q': u'#python',
'lang': 'ja',
'result_type': 'recent',
'count': '15'
}
res = oauth.get(url, params=params)
if res.status_code != 200:
print '[ERROR] Unexpected code: %d' % res.status_code
exit(1)
tweets = json.loads(res.text)
for tweet in tweets['statuses']:
print '-----'
print tweet['text']
実行
$ export TWITTER_API_CONSUMER_KEY=xxx # 以下4行には、「Access Token取得」で得たものを使用します。
$ export TWITTER_API_CONSUMER_SECRET=yyy
$ export TWITTER_API_ACCESS_TOKEN=zzz
$ export TWITTER_API_ACCESS_TOKEN_SECRET=aaa
$ python twitter_api_test.py
結果
こんな感じに。
-----
RT @_liongarden: Pythonエンジニア募集!一緒にクラウドマーケットプレイスをつくりましょ by 株式会社LionGarden https://t.co/REcRr7RdkM #wantedly #python #nodejs #angularjs
-----
RT @_liongarden: Pythonエンジニア募集!一緒にクラウドマーケットプレイスをつくりましょ by 株式会社LionGarden https://t.co/REcRr7RdkM #wantedly #python #nodejs #angularjs
-----
ShannonLabが地元八王子にてpythonの勉強会を定期的に行なっております。プログラミングの初級者の方も参加出来ます。「Python 勉強会 八王子」で検索してね。 ATND から登録出来ます。 #python
-----
RT @_liongarden: Pythonエンジニア募集!一緒にクラウドマーケットプレイスをつくりましょ by 株式会社LionGarden https://t.co/REcRr7RdkM #wantedly #python #nodejs #angularjs
-----
(以下省略)