Yak Shaving

just me

“OAuth2″ For Foursquare on App Engine

without comments

I have playing with Foursquare’s new API v2 to hopefully integrate it into gargoyle.me. Authentication is now a easier than ever, the code below explains how to get a usable auth token to use the API to get data out of Foursquare.

auth.py

foursquare_creds = {
    'key' : 'YOUR_FOURSQUARE_KEY',
    'secret' : 'YOUR_FOURSQUARE_SECRET',
    'return_url' : 'http://redirect_url.appspot.com',
}

foursquare_auth.py

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from django.utils import simplejson
from google.appengine.ext.webapp import template
from auth import foursquare_creds

class Index(webapp.RequestHandler):

    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
        self.response.out.write(template.render(path, {}))

    def post(self):
        """Handle data posted from main form"""
        pass

class FourSquareOAuthRequest(webapp.RequestHandler):
    """Handle the oauth request out to foursquare"""

    def get(self):
        self.redirect("https://foursquare.com/oauth2/authenticate?client_id=%s&response_type=code&redirect_uri=%s" % (foursquare_creds['key'], foursquare_creds['return_url']))

class FourSquareOAuthRequestValid(webapp.RequestHandler):
    """Handle the oauth reply from foursquare"""

    def get(self):
        code = self.request.get('code')
        url = "https://foursquare.com/oauth2/access_token?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s" % (foursquare_creds['key'], foursquare_creds['secret'], foursquare_creds['return_url'], code)
        auth_json = urlfetch.fetch(url, validate_certificate=False)
        access_token = simplejson.loads(auth_json.content)

        # we now have a valid token
        # this token needs to be included with every API request

        friends_url = "https://api.foursquare.com/v2/users/self/friends?oauth_token=%s" % (access_token['access_token'])
        friends_json = urlfetch.fetch(friends_url, validate_certificate=False)
        friends = simplejson.loads(friends_json.content)

application = webapp.WSGIApplication(
                                     [('/', Index,),
                                       ('/auth', FourSquareOAuthRequest),
                                       ('/authreturn', FourSquareOAuthRequestValid)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

For more details see the Foursquare documentation OAuth Docs

Written by channam

June 28th, 2011 at 7:11 am

Posted in Uncategorized

Leave a Reply