Foursquare live updates with the Push API using rails

Posted on Jun 2, 2011

Recently, I have been working extensively with the Foursquare API, also contributing to the open source foursquare2 gem.

While working on these features, I got a sneak peak preview to the new push API through Foursquare. Until I got that, I needed to pull checkins for each user, which was a slow and unefficient process.

Facebook had this feature for a while that for every checkin a user has, the application (he authorized) get a push notification to a callback URL – this is highly effective and more streamlined process.

So, Foursquare added it and like I said, I was happy to get a sneak peak to it.

Since it has no documentation yet, adding it to the application was not as smooth as I am used to, so I thought I would post the code for it on my blog, so you will have it easier then me

Foursquare posts the json for the checkin to your controller with no parameter, so you need to use the post body in order to read it.

Here’s the controller code:

  
class FsRealtimeController < ApplicationController
    
protect\_from\_forgery :except => &#8216;post&#8217;

def post
      
posted_json = request.body.read

if posted_json.blank?
        
render :nothing => true
        
return
      
end

parsed\_json = JSON.parse(posted\_json.to_s)

\# Do whatever you want with the parsed json

render :nothing => true
    
end
  
end
  

The typical json will look something like this:

  
{
  
"checkin": {
  
"createdAt": 1298129668,
  
"id": "4d5fe304d7206ea8e90aeef1",
  
"shout": "#4sqhackathon",
  
"timeZone": "America/New_York",
  
"type": "checkin",
  
"venue": {
  
"categories": [
  
{
  
"icon": "http://foursquare.com/img/categories/building/default.png",
  
"id": "4bf58dd8d48988d125941735",
  
"name": "Tech Startup",
  
"parents": [
  
"Home / Work / Other",
  
"Corporate / Office"
  
],
  
"primary": true
  
}
  
],
  
"contact": {
  
"twitter": "gnrlassembly"
  
},
  
"id": "4c5c076c7735c9b6af0e8b72",
  
"location": {
  
"address": "902 Broadway, 4th Floor",
  
"city": "New York",
  
"crossStreet": "btw 20th and 21st",
  
"lat": 40.739197437761383,
  
"lng": -73.989760279655457,
  
"postalCode": "10010",
  
"state": "NY"
  
},
  
"name": "General Assembly",
  
"stats": {
  
"checkinsCount": 1357,
  
"usersCount": 557
  
},
  
"todos": {
  
"count": 0
  
},
  
"verified": false
  
}
  
},
  
"user": {
  
"firstName": "Neil",
  
"gender": "male",
  
"homeCity": "New York, NY",
  
"id": "2097",
  
"lastName": "Sanchala",
  
"photo": "http://playfoursquare.s3.amazonaws.com/userpix_thumbs/0QYGOJMDGLTJOOQG.jpg",
  
"relationship": "self"
  
}
  
}
  

You can find some more details here (json from the link).