foursquare.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import simplejson as json
  2. import urllib
  3. import requests
  4. ############################
  5. # FOURSQUARE API CONSTANTS #
  6. ############################
  7. AUTHORIZE_URL = 'https://foursquare.com/oauth2/authenticate'
  8. ACCESS_TOKEN_URL = 'https://foursquare.com/oauth2/access_token'
  9. REDIRECT_URL = 'http://localhost:8000/hackathon'
  10. class FoursquareOauthClient(object):
  11. '''
  12. Pytohn client for Foursquare API
  13. '''
  14. access_token = None
  15. def __init__(self, client_id, client_secret):
  16. '''
  17. Parameters:
  18. client_id: String
  19. - The client id from the registering app on Facebook
  20. client_secret: String
  21. - The client secret from the registering app on Facebook
  22. '''
  23. self.client_id = client_id
  24. self.client_secret = client_secret
  25. def get_authorize_url(self):
  26. '''
  27. Obtains authorize url link with given client_id.
  28. Returns:
  29. authURL: String
  30. - The authorization url.
  31. '''
  32. authSettings = {'client_id': self.client_id,
  33. 'response_type': 'code',
  34. 'redirect_uri': REDIRECT_URL}
  35. params = urllib.urlencode(authSettings)
  36. return AUTHORIZE_URL + '?' + params
  37. def get_access_token(self, code):
  38. '''
  39. Obtains access token.
  40. Parameters:
  41. code: String
  42. - The code is retrieved from the authorization url parameter
  43. to obtain access_token.
  44. '''
  45. authSettings = {'client_id': self.client_id,
  46. 'client_secret': self.client_secret,
  47. 'grant_type': 'authorization_code',
  48. 'redirect_uri': REDIRECT_URL,
  49. 'code': code}
  50. params = urllib.urlencode(authSettings)
  51. response = requests.get(ACCESS_TOKEN_URL + '?' + params)
  52. if response.status_code != 200:
  53. raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
  54. self.access_token = response.json()['access_token']
  55. def get_user_info(self, api_version='20140806'):
  56. '''
  57. Obtains user information.
  58. Parameters:
  59. api_version: string
  60. - The API version you would use. This parameter is mandatory by Foursquare.
  61. Returns:
  62. content: Dictionary
  63. - A dictionary containing user information.
  64. '''
  65. USER_INFO_API_URL = 'https://api.foursquare.com/v2/users/self'
  66. authSettings={'v':api_version,
  67. 'oauth_token': self.access_token}
  68. params = urllib.urlencode(authSettings)
  69. response = requests.get(USER_INFO_API_URL + '?' + params)
  70. if response.status_code != 200:
  71. raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
  72. return response.json()['response']['user']