Connect to the Foursquare API via OAuth, Python

by Pete Karl

Everyone's talking about Foursquare, and everyone at my office is flipping obsessed. I chose to participate in the nerdiest way possible I guess.

The following post will break down (and even explain, kinda) a connection to Foursquare's API using OAuth (and Python).

Here's the deal

Oauth is a delightful step away from HTTP authentication for web APIs. By delightful, I mean that it's confusing and not friendly for newbies.

The confusion is exaggerated by the variety of implementations for different service providers. That is, Twitter does it differently than LinkedIn does it differently than Foursquare, and so on.

Think about it like a client-server situation where every request has a little handshake (and some services require you to verify/sign the handshake).

Foursquare & Oauth & Python

1) You'll want to register for an API key with foursquare: http://foursquare.com/oauth/

You'll be using the key and secret that comes up with your registration.

2) This script depends on some sort of python oauth library. I like python-oauth2

Let's roll.

Get a Request Token

We're creating the client part of our relationship here. This includes a 'consumer' object that represents our local auth, and a 'client' object which will make the requests.

We walk away from this transaction with a request_token. Basically, Foursquare is acknowledging that our client exists, and is valid. We carry that acknowledgement in the form of a 'token' object.

Create a signed Request

Now the 'client' part of our client-server equation is ready to rock. With Consumer, Token, and Client in hand, we're ready to start communicating regularly.

Foursquare requires signed requests. Basically, this means that each request we make requires additional verification that it's coming from a trusted source.

In this case, we're created an octet string based on the HMAC-SHA1 text & our secret keys. Just another hash, folks. Nothing to freak out about.

Make the Request

Now that the request is signed, we can fire it off.

That's it! If you have questions, go for it. See the entire example script.

This code was heavily informed by the example documentation on the python-oauth2 github page. Huge thanks to those guys for putting it out there.