そもそもOAuth2.0をどう扱うかもよく知らずに試行錯誤したものだから、結構時間かかってしまった。素直にOAuth2.0の仕組みを理解して、ライブラリの使い方読んだら何てことはなかった。急がば回れ、ですね。
いろいろ作法が違うかもしれませんが、とりあえず動いたので一応めもを残しておくことに。
OAuth2.0をPythonで使うためのライブラリは世の中いろいろあるようですが、Google作成のoauth2clientというライブラリを使ってみました。
まずは、
[bm url=”https://syncer.jp/foursquare-api-matome” description=”Foursquare、SwarmのAPIを使って、施設(ベニュー)や写真、TIPSの情報を取得する方法を初心者向けに解説。”]Foursquare(Swarm) APIの使い方まとめ (サンプルコード付き)[/bm]
を参考に、Client id と Client secret をゲット。Redirect URIは普通はプログラムのURLを記入するわけですが、今回は手元のUbuntuでPythonスクリプト走らせてるだけなので、http://localhost/を指定。
Google Calendar APIのquickstart.pyのget_credentialsをそのまま使わさせていただく。この中で読み込んでいるCLIENT_SECRET_FILEの書き方はGoogleがちゃんと提供していて、それを参考に作る。あまり迷うところはない。(けどここに辿り着くのに時間がかかってしまった)
1 2 3 4 5 6 7 8 9 |
{ "web": { "client_id": "さっき手に入れたClient id", "client_secret": "さっき手に入れたClient secret", "redirect_uris": ["さっき指定したRedirect URI"], "auth_uri": "https://foursquare.com/oauth2/authorize", "token_uri": "https://foursquare.com/oauth2/access_token" } } |
定数は、
1 2 3 4 5 |
# If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = '' CLIENT_SECRET_FILE = 'foursquare_client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' |
こんな感じで。CLIENT_SECRET_FILEはスクリプトと同じ場所に。SCOPESは空に。APPLICATION_NAMEも使わないので空でいいような気がします(使ってる行ごと消した)。
ここまで来たら、あとは叩くだけ。最近のチェックイン5件を取ってきて表示するだけのスクリプト。python3です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import httplib2 import os import urllib import json import time ## quickstart.pyと共通部分は省略 def get_using_oauth(credentials, uri, params={}): http = httplib2.Http() params['oauth_token'] = credentials.access_token params['v'] = '20160922' return http.request(uri+'?'+urllib.parse.urlencode(params)) if __name__ == '__main__': credentials = get_credentials() result = get_using_oauth(credentials, 'https://api.foursquare.com/v2/users/self/checkins',{'limit':'5'}) data = json.loads(result[1].decode('utf-8')) checkins = data['response']['checkins']['items'] for checkin in checkins: checkin_date = time.strftime("%m/%d(%a)", time.gmtime(checkin['createdAt'])) if checkin_date.startswith('0'): checkin_date = checkin_date[1:] checkin_date = checkin_date.replace('/0','/') print('%s に %s へ行きました' % (checkin_date, checkin['venue']['name'])) |
色んなデータの取り方とか、取ってきたデータの見方は先程のサイトを参考に。ここまでくれば、やりたいことは大体できそう。