As part of one of my projects, I'm familiarizing myself with Foursquare's API. Hopefully I will run into some interesting problems I can blog about. Since I found it rather difficult to find good, simple introductory examples on the internet I thought I could share some of the simpler programs I've written. This first one prints Foursquare's categories hierarchically.
Installing the right packages
I'm using mLewisLogic's foursquare library. On Windows, simply download it, extract it and run
python setup.py install
Registering a Consumer
You need to register a consumer on Foursquare's website (Foursquare Consumer Registration). For this example, you can simply insert anything for the application website and the callback url fields. You will need the clientid and a client secret that you get.
Printing the Category Tree
Now that you've installed the package, you're ready to interact with the API. Let's grab the categories:
import foursquare
clientID = 'your client id'
clientS = 'your client secret'
client = foursquare.Foursquare(clientID,clientS)
categories = client.venues.categories()
Before we print the tree, let's take a look at what exactly we've retrieved: We get back a dictionary with a single key called categories.The value for this key is an array of dictionaries. Checking the documentation we see that each of these dictionaries has several keys:
- id
- name
- pluralName
- shortName
- icon
- primary
- categories
print categories['categories'][0]['name']
#outputs Arts & Entertainment
Now the value of the categories key is another array of categories, which isn't too surprising, since we are dealing with a tree. Thus the simplest solution to printing the tree is a recursive function:
import foursquare
def printCategoryTreeRec(categories,n):
for c in categories:
print '\t'*n, c['name']
if "categories" in c:
printCategoryTreeRec(c['categories'],n+1)
clientID = 'your client id'
clientS = 'your client secret'
client = foursquare.Foursquare(clientID,clientS)
categories = client.venues.categories()
printCategoryTreeRec(categories['categories'],0)
This little program will output a long list that looks like:
Arts & Entertainment
Arcade
Art Gallery
Bowling Alley
Casino
Comedy Club
General Entertainment
Historic Site
Movie Theater
Indie Movie Theater
Multiplex
Museum
Art Museum
History Museum
Planetarium
Science Museum
...
And there you go, all of Foursquare's categories!
No comments:
Post a Comment