ほんじゃらねっと

ダイエット中プログラマのブログ

Foursquare API のOAuth認証用クラス

FoursquareAPIを使って場所系のサービスでも作ってやろう、
と思い立って作っている。


APIドキュメントのRate Limitingを読んだところ、
認証済みの場合は認証ユーザー毎、認証していない場合はIPアドレス毎に
1メソッドにつき1時間200アクセスまでと制限されているらしい。
TwitterAPIよりもGoogle App Engineで利用するのは大変じゃなさそう。


ドキュメントはこちら。
http://groups.google.com/group/foursquare-api/web/api-documentation


認証処理はOAuthなのでTwitterの場合とほとんど同じ。
僕はTwitterでAppEngine-OAuth-Libraryを使っていたのだけど、
このライブラリのOAuthClientクラスを継承してFoursquare用のクライアント
クラスを作成して使っている。各URLを変更しただけのもの。


AppEngine-OAuth-Library
http://github.com/mikeknapp/AppEngine-OAuth-Library


作ったクライアントクラスはこんな感じ

foursquare_oauth.py

import logging
from django.utils import simplejson as json
from oauth import OAuthClient
def get_oauth_client(service, key, secret, callback_url):
return FoursquareClient(key, secret, callback_url)
class FoursquareClient(OAuthClient):
def __init__(self, consumer_key, consumer_secret, callback_url):
"""Constructor."""
OAuthClient.__init__(self,
"foursquare",
consumer_key,
consumer_secret,
"http://foursquare.com/oauth/request_token",
"http://foursquare.com/oauth/access_token",
callback_url)
def get_authorization_url(self):
"""Get Authorization URL."""
token = self._get_auth_token()
return "http://foursquare.com/oauth/authorize?oauth_token=%s" % token
def _lookup_user_info(self, access_token, access_secret):
"""Lookup User Info.
        Lookup the user on Foursquare.
        """
response = self.make_request(
"http://api.foursquare.com/v1/user.json",
token=access_token, secret=access_secret, protected=True)
data = json.loads(response.content)
user_info = data["user"]
return user_info

OAuthの具体的な処理については、また機会があったらまとめたい。