Recently in APIs Category

The Google+ Platform 30 Second Experience

It seems like life becomes busier and busier every year. Between longer hours at work and increased obligations elsewhere, who has time to try out a new API? It’s 2012. We only have 3 years to perfect the flying DeLorean!

You say you don’t even have 5 minutes to play with one of the platform starter projects? Well hopefully I can give you a taste of the API in the time you just spent reading this paragraph. You don’t even have to write any code, I promise. (Although I make no promises about inspiration to code that this may cause.)

Since we’ve already wasted 30 seconds babbling, let’s dive into the API already. The easiest way to see the Google+ platform in action is to use the API Explorer. This tool provides point and click access to most of the APIs that Google offers including the REST APIs for Google+.

Since this may be your first time, we’ll keep it simple. Follow these steps to view your public Google+ profile.

  1. Navigate to the API Explorer. To make an API call we must first select the plus service. On the left pane scroll down to and select the plus API. The middle columns will update to display the available versions and methods. api_explorer_1.png
  2. Scanning through the available methods the profile.get method looks like a match, but it requires a userId, which we do not know. We can use the shortcut value of me, but we’ll need to authorize the API explorer to discover our userId. To do this make sure plus.me is selected from the drop down at the top of the window and click on the ‘Switch to Private Access’ link. This will trigger an OAuth popup. Grant the API Explorer permission. api_explorer_2.png
  3. Now that the API Explorer can determine our userId, all we need to do is specify me for the userId and to execute the query. api_explorer_3.png
  4. Upon execution the bottom of the API explorer, the history pane, will display the results of our request. Assuming it was successful we’ll see the HTTP headers from request and response as well as a JSON representation of our public Google+ profile. api_explorer_4.png

Congratulations! If you read fast enough 1 or fewer minutes have incremented on your clock and you’re already using the Google+ APIs. During these four steps we’ve witnessed many important features of the core REST APIs that make up the Google+ platform. We’ve completed the OAuth 2.0 dance to access private information, your userId via the plus.me scope, and observed a fetch of your public profile.

Now that you’ve had a taste of the JSON, you know you want to go grab a starter project, right? :D

Google+ Comments on your Static HTML Blog

Synchronize Comments

Our static HTML blog is pretty cool, but do you know what would make it cooler? Comments would. Discussions about entries can really bring a blog to life, but sadly they come at a cost. Not only do you need to worry about comments from spammers but you also have to expose potentially sensitive software to the outside world.

Fortunately for us, the Google+ public data APIs expose the comments on our activities. Since we’re already sharing our blog posts to Google+ we can use JavaScript to render the comments from the activity right in the blog entry. Not only does this offload the responsibility of spam control to Google, but it also allows us to retain our super simple static HTML blog.

Experiment with the APIs

Before we start writing code lets become comfortable with how the APIs behave. Google provides an API explorer, which is a great way to become familiar with APIs. You can find the API explorer here: https://code.google.com/apis/explorer/

We’ll use this tool to walk through the steps that our comments plugin will follow.

  1. On the left pane scroll down to and select the plus API. The updated view will now display the available methods in the third pane from the left. We can explore these methods and work out a flow for accessing the right comments. api_explorer_1.png
  2. Scanning through the available methods the comments.list method looks perfect, but we need an activity ID to call it. api_explorer_2.png
  3. Just above the comments.list method we find an activities.list method. This will allow us to list our recent activities and determine their IDs for which we can list the comments. api_explorer_3.png
  4. It looks like we need one more piece of information to list our activities: our userId. The easiest way to determine your userId is to copy it out of your Google+ profile URL. profile.png
  5. On the activities.list method paste in your userId and select the public collection. Clicking the execute button triggers the API call and renders the json response in the history pane at the bottom of the page. api_explorer_4.png
  6. The response object consists of some top level attributes and a collection of activities within the items array. Each entry in the items array has an activity ID. Copy the ID for your most recent entry.
  7. We can now switch to the comments.list method and supply the activity ID that we just copied. api_explorer_5.png
  8. With a click of the execute button the history pane on the bottom will be populated with a list of comments associated with that activity.

It looks like we’ve discovered our flow. We can implement a very simple comments integration by manually discovering the activity ID for our share on Google+ and then using JavaScript to fetch the comments associated with it. Once we’ve fetched the comments we can render them within the page.

Registering Our Application

Before we can use the APIs to access public data we must first register our application. Once we register our application we’ll receive an API key that we can use to make requests.

  1. Navigate to code.google.com’s API console: https://code.google.com/apis/console/
  2. Create a new project using the project drop down menu console_1.png
  3. Click on the ‘Services’ link in the API Console menu and toggle the Google+ APIs to ‘on’ console_2.png
  4. Click on the ‘API Access’ link in the API Console menu to access the keys for your new application.
  5. Below ‘Simple API Access’ note your ‘API Key’. We will use this to access the public data APIs below. console_3.png

Time to Code

In our entries we’ll place a div with a special class. We’ll then use JavaScript to replace this placeholder div with the comments for that entry. Here’s an example of a div that our JavaScript will look for:

<div class="g-comments-for z13zevjymuuge1zvl23lyv3a2n3owdxxd04"></div>

Our JavaScript will look for all divs on a page with the g-comments-for class. When it finds one it will fetch all of the comments for the activity whose ID is in the other class.

Create a new JavaScript file comments.js and source it from each blog entry. Within the JavaScript file create a namespace for our functions, because we like to be tidy. Next specify our API key. We’ll need that to make out API calls.

var commentr = commentr || {};
var apiKey = "AIzaSyA-H-eBvhWOyyjIJ2bWeaf1XAn855s8IRN";

Find all of the g-comment-for divs and extract the ID

// search for g-comments-for classes
commentr.go = function() {
    var fetchElements = 
         document.getElementsByClassName('g-comments-for');
    for(var i=0; i<fetchElements.length; i++) {
        var activityId = fetchElements[i].classList[1];
        commentr.fetchComments(activityId);
    }
}

Next, fetch the comments for each activity that we find. Since the Google APIs reside on a different domain name than our blog we’ll use the JSONP response format. For each response this will automatically call a method to inject the comments into our page.

// foreach fetch
commentr.fetchComments = function(activityId) {
    var fetchElement = document.createElement("script");
    fetchElement.src = 'https://www.googleapis.com/plus/v1/activities/' +
        activityId + '/comments?alt=json&pp=1&key=' + apiKey 
        + '&callback=commentr.praseComments';
    document.body.appendChild(fetchElement);
}


// when fetch completes, parse the response and insert the records
commentr.praseComments = function(resposneJson) {
    var activity = resposneJson.items[0].inReplyTo[0];
    var comments = resposneJson.items;

    //find element to insert into
    var insertionElements = document.getElementsByClassName('g-comments-for ' +
        activity.id);
    var insertionElement = insertionElements[0];

    var newContents = "";
    for(i=0; i<comments.length; i++) {
        var actor = comments[i].actor;

        var commentBody = comments[i].object.content;

        //do the insertion
        newContents += "<dt><a href='" + actor.url + 
            "'><img src='" + actor.image.url + "' /></a></dt>" + 
            "<dd><a href='" + actor.url + "'>" + actor.displayName + 
            "</a>: " + commentBody + "</dd>";

    }
    insertionElement.innerHTML = "<dl>" + newContents + 
        "</dl> <p class='g-commentlink'>Please comment on the <a href='" + 
        activity.url + "'>Google+ activity</a></p>";   
}

And finally we need to add register our plugin to execute after the page loads.

// Append our program to the window.onload
document.addEventListener("DOMContentLoaded", commentr.go, false);

Comments Integration in Action

That was pretty easy, wasn’t it? Now lets see it in action.

Using the API explorer we can find the activity ID of our most recently public entry. In this case it’s z13zevjymuuge1zvl23lyv3a2n3owdxxd04. Go back to the HTML code for that entry and add the magic div that inserts the comments.

<div class="g-comments-for z13zevjymuuge1zvl23lyv3a2n3owdxxd04"></div>

Reload the page and see the rendered comments!

result.png

What’s Next?

Our comments plugin was very easy to write, but this simplicity comes at a cost. It’s quite brittle and requires us to use the API explorer to discover the activity ID for each entry that we share. A good companion to this plugin would be a tool which fetches our most recent activities and renders a div that we can paste into our entries.

Code and Demo

See it in action on Baking Disasters

Access the code (without using copy and paste) on Google Project Hosting

SOAP vs REST

To understand SOAP and REST you must first understand web services. A web service is a method by which two pieces of software can communicate over a computer network, such as the Internet. SOAP and REST are two different approaches to satisfying this need. They differ in many ways such as their design philosophies, the concepts they define, the effort involved in using them and how they interact with HTTP.

SOAP, Simple Object Transfer Protocol, is built upon the design philosophy of remote procedure calls. In this way SOAP allows software to connect over a network and invoke behavior in other software. This ability solves a common problem in large-scale distributed software systems often found at large enterprises. On the other hand, REST, also known as Representational State Transfer, draws from very different design philosophies. It is based upon the concept of exchanging data. REST web services aim to exchange data as simply as possible by leveraging what is already available.

Since these two techniques differ in philosophy, they also differ in what they define and what they leave up to the implementer. Where SOAP defines a specific format for message exchange using XML, REST does not require any specific format to be used. REST does however constrain the actions performed by a service to those provided by the transfer protocol on which is operates. SOAP allows for any number of methods to be defined thereby providing more flexibility in the behaviors that clients can use.

Implementations of REST and SOAP are also very different. Despite its name, SOAP is a very complicated protocol governed by a set of formal specifications. Implementations often involve large toolkits and are assisted by other protocols like WSDL. Additionally, since behavior is being invoked from a remote system, security is a major concern. Conversely, REST is a general concept that relies mainly on other existing standards to define itself. As a result REST web services can be implemented more easily without the need for REST specific toolkits.

While theoretically a web service can be implemented on top of any data transfer protocol, web services almost always use the ubiquitous HTTP. This is the same protocol your web browser uses to load web pages. REST web service designs attempt to harmonize with HTTP by using its existing vocabulary including both the verbs of HTTP, such as get and post, and the response codes, such as 400 for a user error. This allows REST web services to leverage existing HTTP reliability and scaling technologies quite easily. SOAP, however, is more concerned with consistency regardless of the data transfer protocol used. As a result it draws very little from existing HTTP concepts. SOAP instead defines its own vocabulary, which must be interpreted in addition to HTTP for an integration to function.

In the end SOAP and REST are very different approaches to solving slightly different sets of problems. REST based web services may be easier create and integrate; but some problems, such as system wide distributed transactions, can be more straightforward to implement using behavior centric models like SOAP.

Nearby Events on Eventbrite

Welcome back!

It’s time to continue exploring the Eventbrite APIs. Today we’ll write a very simple PHP page finds events very close to a specific latitude and longitude using the event_search API.

What You Need

Something to Start From

We are not here to learn about writing forms in PHP, so to get us started here is the skeleton of an application to which we will add Eventbrite functionality.

<?php
$app_key = "exampleApiKey"; //Supply your Eventbrite App Key here.  Remember to keep your App Key secure!

if (!(isset($_GET['latitude']) && isset($_GET['longitude']))) {
    //No coordinates are set. Display a very simple form to request a latitude and longitude
    ?>

    
Latitude Longitude
<?php } else { //We have coordinates! Lets get busy. //Normally we'd validate the input here, but we'll skip that ugly stuff $latitude = $_GET['latitude']; $longitude = $_GET['longitude']; print "I will search for events near lattitude $latitude longitude $longitude.

\n"; }

Go ahead. Paste it into your editor and see how it works. On first load it will display a form with two fields: one for latitude and one for longitude. When submitted the page will print the supplied latitude and longitude values.

Constructing the Query

To fetch a list of events we must query the event_search API. All we need to do is to put together a URL that specifies our event search filters. For this tutorial we need to specify three parameters. Two of these come from our form: latitude and longitude. The third, within distance, we will hard code for the sake of this example. 1 mile seems like a reasonable within distance.

$request_url = "https://www.eventbrite.com/xml/event_search/?app_key=$app_key&latitude=$latitude&longitude=$longitude&within=1";

Executing the Request and Interpreting the Response

We can now use our favorite PHP HTTP client, cURL, to execute our freshly created API request.

After we execute the request we can parse and interpret the response. If the API request failed, we expect to see an <error> element at the root of the document. This element will contain an <error_message> element. We will display an error message if it is available.

Under normal conditions our API request will not contain an <error> element. In this case the response contains an <events> element with a single <summary> element and many <event> elements as children. We will display the total number of discovered events and list the titles of each event returned. Note that this API uses paging, so for popular areas not all event titles will be printed.

    //Next, lets hit the API with cURL
    $ch = curl_init($request_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response_body = curl_exec($ch);

    //We have our result in a string. Lets parse it.
    $xml = new SimpleXMLElement($response_body);

//    var_dump($xml); //Uncomment this line to see the entire parsed response

    //Check our parsed response for problems (such as an errors element). If there's an issue, let our user know.
    if ($xml->error_message) {
        //something is up here
        $error_message = $xml->error_message;
        print "Eventbrite responded with an error: $error_message

\n"; } else { //Things are looking good. We can start by printing some of the response summary data print "I found " . $xml->summary->total_items . " nearby events. Here are the titles from the first page of results: \n"; //The bulk of our response is a list of events. Let's display each event title. print "
    \n"; foreach ($xml->event as $event) { print "
  1. " . $event->title . "
  2. \n"; } print "
\n"; } //some boilerplate clean-up stuff curl_close($ch);

The Result

Visit this PHP page and supply the latitude and longitude for a location that is likely to have some upcoming events. Try a latitude of 37.78 and a longitude of -122.4. This will search a populated part of San Francisco.

You should see something like this:

I will search for events near lattitude 37.78 longitude -122.4.

Hitting https://www.eventbrite.com/xml/event_search/?app_key=APP_KEY&latitude=37.78&longitude=-122.4&within=1 to find nearby events.

I found 369 nearby events. Here are the titles from the first page of results:

  1. Manor West
  2. Signature Series at MANOR WEST DJ Z-TRIP
  3. “Signature Series” at Manor West ~ featuring Yolanda Be Cool: “We No Speak Americano”
  4. Elite Session With STIMMING
  5. FIP Seminar at San Francisco WestEd
  6. Bridal Stylist Training & Certification
  7. Image Consultant Certification Training
  8. Learn Color Analysis Get Certified Too!
  9. MAKEOVER YOU and Get the Date, Job, Money!!
  10. City Nights Mardi Gras 2011 featuring DJ CLASS

Knock It Up a Notch

We have a list of events within a mile of our latitude and longitude. If we happen to be carrying our GPS and are simply curious about what is going on around us, this may be useful, but there is so much more that we can do with this API. Here are a few ideas for features that you may wish to add to our search tool:

All of the Code

Did some of my instructions confuse you? Would you like to skip all my wordy explanation and just hack at the code? If so, here is the complete code for this tutorial.

Enjoy!

<?php
$app_key = "exampleApiKey"; //Supply your Eventbrite App Key here.  Remember to keep your App Key secure!

if (!(isset($_GET['latitude']) && isset($_GET['longitude']))) {
    //No coordinates are set. Display a very simple form to request a latitude and longitude
    ?>

    
Latitude Longitude
<?php } else { //We have coordinates! Lets get busy. //Normally we'd validate the input here, but we'll skip that ugly stuff $latitude = $_GET['latitude']; $longitude = $_GET['longitude']; print "I will search for events near lattitude $latitude longitude $longitude.

\n"; //First, we need to construct our request URL $request_url = "https://www.eventbrite.com/xml/event_search/?app_key=$app_key&latitude=$latitude&longitude=$longitude&within=1"; print "Hitting $request_url to find nearby events.

\n”; //Next, lets hit the API with cURL $ch = curl_init($request_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response_body = curl_exec($ch); //We have our result in a string. Lets parse it. $xml = new SimpleXMLElement($response_body); // var_dump($xml); //Uncomment this line to see the entire parsed response //Check our parsed response for problems (such as an errors element). If there’s an issue, let our user know. if ($xml->error_message) { //something is up here $error_message = $xml->error_message; print “Eventbrite responded with an error: $error_message

\n”; } else { //Things are looking good. We can start by printing some of the response summary data print “I found ” . $xml->summary->total_items . ” nearby events. Here are the titles from the first page of results: \n”; //The bulk of our response is a list of events. Let’s display each event title. print “
    \n”; foreach ($xml->event as $event) { print “
  1. ” . $event->title . “
  2. \n”; } print “
\n”; } //some boilerplate clean-up stuff curl_close($ch); }

Getting Started With Eventbrite APIs

Hello!

It’s time for a bit of a departure from my usual blog structure. Instead of writing about a specific annoying error message and SEOing the heck out of it, I’ll be writing a short series of posts describing a new set of APIs that I’m playing with: the Eventbrite APIs.

The Eventbrite APIs are roughly RESTful. This is very good news. We can begin our exploration using off-the-shelf tools like command line cURL.

First we’ll experiment with failure and success in searching for an event, a read operation. Once we have a handle on reads, let’s create a new event.

What You Need

  • Command line cURL (You already have this if you are on OS X or Linux. Try Cygwin if you are on Windows.)
  • An Eventbrite app key
  • Your Eventbrite user key for creating data

Fail First

To clearly understand success, it’s often importnat to fail at least once. Understanding this failure makes it easier to identify success.

From the event_search reference documentation we can see that an app_key parameter is required. Let us access the API without specifying one to see what happens.

$  curl -i 'https://www.eventbrite.com/xml/event_search'
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 19 Feb 2011 09:51:43 GMT
Content-Type: application/xml
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache, must-revalidate, no-cache="Set-Cookie", private
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Vary: Accept-Encoding


        Please provide your Application Key in the URL as "?app_key=".
        Application Key Error

$ 

Did you notice anything interesting? The response body is as expected, an xml document describing our missing app_key, but check out the HTTP response headers. The status is 200 OK. You may have expected an HTTP 400 response of some kind since the request failed. We now know that the API may respond indicating success even when there is a problem. We cannot rely on the HTTP status in our application and must always parse the response body and check errors.

Success in Search

As we saw above, failing on purpose teaches us important lessons, but success is much more satisfying. Let’s add our api_key into our query URL and observe success.

$ curl -i 'https://www.eventbrite.com/xml/event_search?app_key=exampleApiKey'
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 19 Feb 2011 10:05:10 GMT
Content-Type: application/xml
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache, must-revalidate, no-cache="Set-Cookie", private
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Vary: Accept-Encoding


    
        
        
        12058066
        46957451
        10
        42114
    
    
        ... a very long list of events ...
    

$

As we hoped, there is a long list of event elements in the response body. The list of events is a bit arbitrary, since we did not specify any filters, but that is no surprise.

Try some queries with filters and observe the narrowing of the response list. Here are some URLs to get you started:

  • https://www.eventbrite.com/xml/event_search?app_key=exampleApiKey& keywords=google%20OR%20multimedia
  • https://www.eventbrite.com/xml/event_search?app_key=exampleApiKey&postal_code=94107
  • https://www.eventbrite.com/xml/event_search?app_key=exampleApiKey&date=today
  • https://www.eventbrite.com/xml/event_search?app_key=exampleApiKey&count_only=true

Creating an Event

Searching events is pretty powerful, but a proper application

$  curl -i 'https://www.eventbrite.com/xml/event_new?app_key=exampleApiKey&user_key=exampleUserKey&title=test&description=testDescription&start_date=2012-12-31%2010:00:00&end_date=2013-01-01%2002:00:00&timezone=GMT+01'
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 19 Feb 2011 10:43:46 GMT
Content-Type: application/xml
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache, must-revalidate, no-cache="Set-Cookie", private
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Vary: Accept-Encoding


        1341790331
        event_new : Complete 
        (Draft)
        OK

$ 

It looks like we’ve created an event! You can see this event in your My Events page.

You have probably already figured this out, but even though we made an HTTP GET request, which is supposed to be repeatable, be careful not to repeat this query as it will create additional events.

Conclusion

In just a few short minutes, without writing a single line of code, we have learned a lot about the Eventbrite API. Taking care to look before we leap can save us countless hours down the road.

Armed with some new facts about the Eventbrite API, it’s time to fire up our favorite text editor or IDE. You guessed right, it’s time to code!