Finding your way around the Foursquare API

Getting to grips with the social media Application Program Interface

A FourSquare API Guide

Recently I have been getting to grips with the Foursquare API.

I really love playing with APIs and the data you can tap in to is often very impressive.
The key data to draw from 4sq is the user check-ins to see where a person has been. From this you can then build upon the data with various visulisations or validations, such as:

  • Visualising check-ins on a map
  • Comparing user check-in history
  • Customer Loyalty apps
  • The most important part is establishing a method to perform the API calls and properly handle the data returned.
    The official Foursquare developer portal has a lot of good information to assist with this, but below is an open source app written by myself.

    Creating a Foursquare App

    Step one is to create an app on the Foursquare platform.
    This generates the unique access codes for the API data used to validate and limit API requests.

    Start by visiting: https://developer.foursquare.com/ and clicking “Get Started”

    Follow the prompts to create a new app and fill out the new app registration form as seen here:
    Register a Foursquare App

    Register a Foursquare App

    Once registered we need to make a note of the Client ID and Client Secret:

    Foursquare Client ID

    Coding the App

    Now we have the API access tokens we need, we can begin to code the app to utilise the API data.

    In this post we will look at an example app to check the user check-ins against a predetermined list of locations.

  • Step one: Get user authentication for the app and get the access token that allows access to the users check-in data.
  • Step two: Save the user authentication to a cookie to prevent repeat authentication requests
  • Step three: Define the array of locations to check against
  • Step four: Define the time period to check against
  • Step five: Pull the data from the API and parse out the JSON output
  • Step six: Loop through the results, comparing them against the defined array
  • Step seven: Output the results
  • To check for user authentication we can first check for the “code” passed as a GET parameter in the URL.
    This would be the case if the user landed on the page immediately after authenticating the app.

    Next we add at the user access token to a cookie to prevent re-authentication for each return visit:

    <?php
    if (isset($_GET["code"]))
    {
    $code = $_GET["code"];
    $resp=file_get_contents('https://foursquare.com/oauth2/access_token?client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&grant_type=authorization_code&redirect_uri=http://www.your-URL.co.uk/4sq&code='.$code);
    $obj = json_decode($resp);
    setcookie('acc',$obj->{'access_token'}); 
    }

    Once this is done we need to confirm that the authentication token is stored in the cookie, and then establish the count variable as 0:

    if (isset($_COOKIE['acc'])){
    $token = $_COOKIE['acc'];
    $i=0;

    Next we define the array of venues to check against and define the timescale to be checked.
    We then make the API request and decode the returned JSON:

    //Venues to check against
    $carray =  array("Mindshare", "Bay Central Towers", "c-base", "Mein Haus am See");
    //Timestamp to check against
    $time = "1363864582";
    $resp=file_get_contents('https://api.foursquare.com/v2/users/self/venuehistory?afterTimestamp='. $time. '&oauth_token='.$token.'&v=20130327');
    $obj = json_decode($resp, true);

    Now we can begin to loop through the data returned from the API call and match it against the array we defined in the step above.
    As we loop through the results we increase the tally, stored under the variable $i, for each positive result.
    Once this is done we can output the results to the user, showing how many of the chosen venues the user has visited in the specified time frame.

    foreach($obj['response']['venues']['items'] as $items ){
        $checkthis = $items['venue']['name'];
     
    foreach($carray as $string)
     {
     if(strpos($checkthis, $string) !== false) 
      {
        $i++;
        break;
      }
    }	
    }
    echo "You have been to ".$i." of the selected venues in the last week";	
    }

    Finally we close the code by sending the user to the authentication page if no auth cookie is set or the URL does not contain the GET parameter from a sucessful authentication:

    else{
    header('Location: https://foursquare.com/oauth2/authenticate?client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&response_type=code&redirect_uri=http://www.your-URL.co.uk/4sq');
    }

    Put the whole thing together, and it looks like:

    <?php
    if (isset($_GET["code"]))
    {
    $code = $_GET["code"];
    $resp=file_get_contents('https://foursquare.com/oauth2/access_token?client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&client_secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&grant_type=authorization_code&redirect_uri=http://www.your-URL.co.uk/4sq&code='.$code);
    $obj = json_decode($resp);
    setcookie('acc',$obj->{'access_token'}); 
    }
    if (isset($_COOKIE['acc'])){
    $token = $_COOKIE['acc'];
    $i=0;
    //Venues to check against
    $carray =  array("Mindshare", "Bay Central Towers", "c-base", "Mein Haus am See");
    //Timestamp to check against
    $time = "1363864582";
    $resp=file_get_contents('https://api.foursquare.com/v2/users/self/venuehistory?afterTimestamp='. $time. '&oauth_token='.$token.'&v=20130327');
    $obj = json_decode($resp, true);
     
    foreach($obj['response']['venues']['items'] as $items ){
        $checkthis = $items['venue']['name'];
     
    foreach($carray as $string)
     {
     if(strpos($checkthis, $string) !== false) 
      {
        $i++;
        break;
      }
    }	
    }
    echo "You have been to ".$i." of the selected venues in the last week";	
    }
    else{
    header('Location: https://foursquare.com/oauth2/authenticate?client_id=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&response_type=code&redirect_uri=http://www.your-URL.co.uk/4sq');
    }
    ?>

    And there you have it!

    Give it a try: danclarkie 4sq app

    A simple Foursquare app in less than 45 lines of code.
    Hopefully this will reduce your learning curve in working with the Foursquare API and makes it easier to build on the data this API provides.