Preflight

Webkit
If using Google Chrome, you will likely need the Dev channel to see all of the functionality in this presentation. If you are using Safari, you will likely need a nightly build of WebKit in order to see all of the functionality in this presentation.
Mozilla
You are running a Mozilla browser. While such browsers generally have excellent support for HTML5 features, this presentation has only been tested using WebKit browsers such as Google Chrome or Safari. You should still be able to navigate the slides by using left/right arrow keys, but will currently see display errors with regard to the 3d rendering of the slides and some demo content.
Other browser
You are running a browser that has not been tested with this presentation. You may not be able to run some or all of the samples listed here. While we want to add support for as many browsers as possible, currently we only support WebKit-based browsers such as Google Chrome or Safari.
If things look good, press → to move on.
Welcome! (This field is for presenter notes and commentary.)
Press:
  • Space or ← / → to move around
  • Ctrl/Command / – or + to zoom in and out if slides don’t fit
  • N to show/hide speaker notes
  • H to highlight important elements in code snippets

Working with Web APIs
Featuring:
Google Gadget and Google+ APIs

Blaine Bublitz
http://gplus.to/phated
@YarrSoftware
Phated on Github
This Presentation Will Cover
  1. A Quick Overview of APIs
    • Traditional
    • Web Services
    • Web APIs
  2. An Example of a Web API
  3. A Guide for Working with Google APIs
    • Google Gadget
    • Google+
    • Google Hangouts
Why Google+ and Hangout APIs?

HTML5 Hackathon - Mountain View, CA - 8/11/11
API?
  • Application
  • Programming
  •  I nterface
  • (Very) General Definition:
    A specification that exposes portions of an application's code and allows applications to communicate with each other.
An API is an interace that facilitates interaction between different software, much in the same way that a user interface (UI) facilitates interaction between a human and a program.
Traditional API - Swing Example! Circa 1998!
import java.awt.FlowLayout;
import com.sun.java.swing.*;

public class SwingExample {
  public static void main(String[] args) {
 SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        JFrame f = new JFrame("Swing Example Window");

        f.setLayout(new FlowLayout());

        f.add(new JLabel("Hello, world!"));
        f.add(new JButton("Press me!"));

        f.pack();

        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        f.setVisible(true);
      }
    });
  }
}
HTTP!! - Web Services

Web Services:

APIs over HTTP (But not Web APIs)
  • Standard defined by the W3C
  • Protocol for applications to communicate over HTTP
  • Defined by a WSDL
  • Clients communicate with SOAP messages
  • XML Serialization of messages
  • Typically implements Remote Procedure Calls
Problems & Concerns with Web Services
  • Too Complex
  • Based on large software vendors' technologies (very few open source implementations)
  • When created by toolkits, web services often break when changes to code or the SOAP stack are made due to changes in the WSDL
  • Performance concerns due to use of XML for messages & SOAP/HTTP for enveloping and transport

Well, then... What are our other options?!?!

One Option: Web Services with SOA
Service-Oriented Architecture (SOA): A web service which uses messages, instead of operations (RPCs), to communicate with clients.
Server with SOA
interface defined
Client aware of
SOA on server
<------------------------------------------------------------- "I want a Sammich"
"Here is your Sammich!" ------------------------------------>
SERVER
Y U NO LET ME CHOOSE SAMMICH?!
Option 2: Web APIs

Web APIs: RESTful Web Services

They define:
  • A set requests
  • The structure of response messages
They use (typically):
  • HTTP requests
  • XML or JSON reponse messages
Representational state transfer (REST)

What is REST?

Or better yet, what is it NOT?
  • NOT a Protocol (which SOAP is)
  • NOT an "official" standard (but can implement standards)
  • NOT a pain in your ass (again, like SOAP)
Okay, what REST is!
  • IS an architecture
  • IS a characterization and constraint of the interactions between participants on the web (governing their behavior)
  • IS built upon requests and responses between clients and servers
Constraints? We don't need no stinkin' constraints!

Constraints described by the REST architectural style

  • Client–server
  • Stateless
  • Cacheable
  • Layered system
  • Code on demand (optional)
  • Uniform interface
Well Then, Why be RESTful?

Benefits of the REST architectural style

  • Performance
  • Independence
  • Generality
  • Scalability
  • Simplicity
  • Modifiability
  • Visibility
  • Portability
  • Reliability
  • Intermediary Components
Show me a RESTful Sammich!
Resource GET PUT POST DELETE
Collection URI, such as http://sammiches.nodester.com/sammiches/ List all Sammiches. Replace all Sammiches with new Sammiches. Create a new Sammich. Delete all Sammiches.
Element URI, such as http://sammiches.nodester.com/sammiches/turkey Show a Turkey Sammich. Update a Turkey Sammich (if exists), or create it (if not exists). Treat as a collection and create a new Sammich in it. Delete a Turkey Sammich.
A better RESTful Sammich!
Resource GET PUT POST DELETE
Collection URI, such as http://sammiches.nodester.com/sammiches/ List all Sammiches. Replace all Sammiches with new Sammiches. Bulk update all Sammiches Create a new Sammich. Delete all Sammiches.
Element URI, such as http://sammiches.nodester.com/sammiches/turkey Show a Turkey Sammich. Update a Turkey Sammich (if exists), or create it Error (if not exists). Treat as a collection and create a new Sammich in it. Error Delete a Turkey Sammich.
Enough with the Theory, Let's Look at Some CODE!
Google Gadget
Google+
Google+ Hangouts
Google Gadget What is a Gadget?

Simple Web Application

Useful because:
  • Easy to create
  • Can run in different places
  • Reach users
Google Gadget Where do Gadgets run?
    Integrated into Google infrastructure, including:
  • Gmail
  • Google Calendar
  • iGoogle
  • orkut
  • Google Maps
  • Google Sites
  • And now: Google Hangouts!
Google Gadget Hello Sammiches!
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Hello Sammiches example" />
  <Content type="html">
     <![CDATA[ 
       Hello, Sammiches!
     ]]>
  </Content>
</Module>
Gadget Demo!

Content References
Module Pref References
Google Gadget User Preferences
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="User Preferences for __UP_username__" height="400" />
  <UserPref name="username" display_name="Name" required="true"/>
  <Content type="html">
     <![CDATA[ 
       <div id="content"></div>
       <script type="text/javascript" 
           src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
       </script>
       <script type="text/javascript">
         // Get userprefs
         var prefs = new gadgets.Prefs();
         
         $('#content').html('Hello, ' + prefs.getString('username') + 
                            '<br> Would you like a Sammich?');
       </script>
     ]]>
  </Content>
</Module>
Gadget Demo! User Pref References
Google Gadget XML is well and good, but I <3 JavaScript
Important ---> JS References
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="User Preferences for __UP_username__" height="400">
    <Require feature="tabs"/>
  </ModulePrefs>
  <Content type="html">
     <![CDATA[ 
       <script type="text/javascript">
         // gadgets.TabSet(opt_moduleId, opt_defaultTab, opt_container)
         var tabs = new gadgets.TabSet();
         for(var x = 0; x < 4; x++){
            var tab_Id = tabs.addTab("tab" + x); // String addTab(tabName, opt_params)
            document.getElementById(tab_Id).innerHTML = "Content for tab " + x;
         }
       </script>
     ]]>
  </Content>
</Module>
Gadget Demo!
Google Gadget What is available in the Gadget JS Namespace?
Core API
(always available)
  • Prefs
  • io
    • AuthorizationType
    • ContentType
    • MethodType
    • ProxyUrlRequestParameters
    • RequestParameters
  • json
  • util
Feature-Specific API
(require <Require />)
  • MiniMessage
  • Tab
  • TabSet
  • flash
  • pubsub
  • rpc
  • skins
    • Property
  • views
    • View
    • ViewType
  • window
Gadget API References
Google+ The Plusification of Google

Google+ Plugins

  • +1 Button
  • Badge
Google+ +1 Button

Make it easy for users to share content on your website on Google+

Basic Syntax:
<script type="text/javascript" src=
"https://apis.google.com/js/plusone.js"></script>


<g:plusone></g:plusone>		
More Info at +1 Button Plugin Page
Google+ Hey a-hole, you're blocking loading and not compliant!
<!-- YAY (HTML5) COMPLIANCE! -->
<div class="g-plusone" data-size="tall" ... ></div>

<!-- Async Loading - Huzzah! Non-blocking! -->
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); 
    po.type = 'text/javascript'; 
    po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(po, s);
  })();
</script>
Google+ +Snippet Content

+Snippet = Information posted to G+ Profile when page is +1'ed

  1. Schema.org microdata (recommended)
  2. Open Graph protocol
  3. Title and Description meta tags
  4. Google's best guess from page content (not recommended)
More Info at +Snippet Documentation Page
Google+ +1 Button: +1 Last Thing

Where does the +1 Button get the URL from?

  1. The href attribute on the button
  2. The <link rel="canonical" ... /> of the page
  3. The URL retrieved by document.location.href (not recommended)
More Info at Target URL Documentation Page
Google+ Google+ Badges

Google: "Not yet fully available, but will be coming soon"

  1. Only Static Icons (No Dynamic Badges Yet)
  2. Dynamic Badges and Static Icons!!!
  3. Links your website to your Google+ Page
  4. Helps consolidate all your +1's
  5. Eligibility for Google+ Direct Connect
More Info at Google+ Badge Plugin Page
Google+ Google+ Direct Connect

Want to be Searchable with +PageName?

Use (in the <head>):
<link href="{plusPageUrl}" rel="publisher" />
Or (in the <body>):
<a href="{plusPageUrl}" rel="publisher"></a>
Google+ This Just In! - Google+ Badges
<script type="text/javascript" src=
"https://apis.google.com/js/plusone.js"></script>

<g:plus href="{plusPageUrl}" size="badge"></g:plus>

<!-- HTML5 Compliant -->
<div class="g-plus" data-href="{plusPageUrl}" data-size="badge">
</div>	
Google+ Google+ Static Icon
<!-- Place this tag in the <head> of your document-->
<link href="{plusPageUrl}" rel="publisher" />

<!-- Place this tag where you want the badge to render-->
<a href="{plusPageUrl}?prsrc=3" 
  style="text-decoration: none; color: #333;">
  <div style="display: inline-block; *display: inline;">
    <div style="text-align: center;">
      <img src="https://ssl.gstatic.com/images/icons/gplus-64.png"
        width="64" height="64" style="border: 0;"/>
    </div>
    <div style="font: bold 13px/16px arial,sans-serif; 
      text-align: center;">Blaine Bublitz</div>
    <div style="font: 13px/16px arial,sans-serif;">
     on Google+ </div>
  </div>
</a>
Google+ Putting It All Together (When Fully Implemented)
<head>
  <link href="{plusPageUrl}" rel="publisher" />
  <!-- Optional (if not specified, use href on +1 element -->
  <link rel="canonical" href="{pageUrl}" />
</head>
<body itemscope itemtype="http://schema.org/Product">
  <div class="g-plus" data-href="{plusPageUrl}" data-size="badge"></div>
  <div class="g-plusone" data-size="tall"></div>
  <h1 itemprop="name">Shiny Trinket</h1>
  <img itemprop="image" src="image-url" />
  <p itemprop="description">Shiny trinkets are shiny.</p>
  <script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  </script>
</body>
Google+ Plugin Tools

+1 Button Configuration Tool


Badge Configuration Tool

Google+ G+ APIs: What is available to us?
Google+ Why is G+ API support so limited?

Just a Sample

Why? Feedback and Learning

Restrictions? Read Only, Public Data, Usage Quota

Google+ Retrieve a Profile as JSON
GET https://www.googleapis.com/plus/v1/people/102147307918874735077
?key=API_KEY&alt=json
Google+ What Parameters are available to the API?
Parameter Name Value Description
callback string Specifies a JavaScript function that will be passed the response data for using the API with JSONP.
fields string Selector specifying which fields to include in a partial response.
key string API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
access_token string OAuth 2.0 token for the current user. Learn more about OAuth.
prettyPrint boolean If set to "true", data output will include line breaks and indentation to make it more readable. If set to "false", unnecessary whitespace is removed, reducing the size of the response. Defaults to "true".
userIp string Identifies the IP address of the end user for whom the API call is being made. This allows per-user quotas to be enforced when calling the API from a server-side application. Learn more about Capping Usage.
Google+ What Resources Can We Retrieve?
  • People
  • Activities
  • Comments
  • But only when they are Public! <LAME!>

Google+ Ways to Retrieve People
get
Get a person's profile.
GET https://www.googleapis.com/plus/v1/people/{userId}
search
Search all public profiles.
GET https://www.googleapis.com/plus/v1/people?query=SEARCH_STRING
listByActivity
List all of the people in the specified collection for a particular activity.
GET https://www.googleapis.com/plus/v1/activities/{activityId}/people/{collection}
Google+ Ways to Retrieve Activities
list
List all of the activities in the specified collection for a particular user.
GET https://www.googleapis.com/plus/v1/people/{userId}/activities/{collection}
get
Get an activity.
GET https://www.googleapis.com/plus/v1/activities/{activityId}
search
Search public activities.
GET https://www.googleapis.com/plus/v1/activities?query=SEARCH_STRING
Google+ Ways to Retrieve Comments
list
List all of the comments for an activity.
GET https://www.googleapis.com/plus/v1/activities/{activityId}/comments
get
Get a comment.
GET https://www.googleapis.com/plus/v1/comments/{commentId}
Google+ One Last Thing: OAuth or API key

No authentication = No API access

Types of Authentication:

  • API Key - Public
  • OAuth 2.0 - Private (or Public)

Still a Preview/Beta = No Private Data

Google+ A Couple Important Tools

Standalone Google API Explorer


Google APIs Console

Hangouts When Google Implements Your Plugin Natively...
Hangouts What is a Hangout App?

Basically just a Google Gadget

What makes them special?

They can interact with the real-time functionality
Hangouts Look Familiar?
<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Your App Name">
    <Require feature="rpc"/>
    <Require feature="views"/>
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
      <script src="https://hangoutsapi.talkgadget.google.com
      	/hangouts/api/hangout.js?v=0.1">
      </script>
      <!-- Your application code -->
    ]]>
  </Content>
</Module>
Hangouts Important Aspects: Events

Events

  • Event = Object containing 2 functions: add & remove
  • on*.add(callback) and on*.remove(callback)
  • Pro-Tip: start your app's code by passing a callback to onApiReady.add(), such as:
gapi.hangout.onApiReady.add(function(eventObj){
  if (eventObj.isApiReady) {
    startMyApp();
  }
));
Hangouts Important Aspects: Application State

Application State

  • State object = single instance shared across all apps in Hangout
  • Restriction: data values must be stored as strings
  • Pro-Tip: use JSON.stringify(obj) and JSON.parse(obj)
  • Access and manage using API functions in the gapi.hangout.data namespace
Hangouts Available Namespaces
namespace gapi.hangout
Provides basic information such as the list of participants, the locale, and whether the app is initialized and visible.
namespace gapi.hangout.av
Provides functions for controlling hangout microphones, cameras, and speakers.
namespace gapi.hangout.data
Provides functions for sharing data (getting and setting gadget state) between every instance of a gadget in a hangout.
namespace gapi.hangout.layout
Provides functions for getting and setting layout elements in the Hangout user interface.
Gadget Google+ Hangouts Example!

Example XML


API Console

Google+ What Can We Do Until Google Releases a Full API?

Special Thanks to Mohamed Mansour

Author of the Unofficial G+ API (Just Released on Sunday!)

Find it on Github: mohamedmansour/google-plus-extension-jsapi

Google+ What is Different in the Unofficial API?

Would You Like to Read or Write:

  • Circles?
  • Followers?
  • Profile (Public or Private)?
  • Streams (Public or Private)?

All of This is Yours! --- With the Unofficial APIs!

Google+ How is that Possible?

Reverse Engineering

Mohamed spent a LOT of time using the Chrome Developer Tools to capture the XHRs and parsed the obfuscated data.

The API captures the data, parses it, and adds it to a WebSQL DataStore. Also, it exposes methods for easy access to that DataStore.

More Info on G+

And on Github

Information Overload!
  • API Defined
  • Traditional API
  • Web Services
  • SOA
  • Web APIs
  • REST Architecture
  • Google Gadget API
  • Google+ Plugins
  • Google+ API
  • Google Hangout API
  • Unofficial API

Thanks!

Questions or Feedback?

Find Me Online:

  • Blaine Bublitz on Google+
  • YarrSoftware on Twitter
  • Phated on Github
  • Link to Slides: http://goo.gl/sMBE5

References
  • Mohamed Mansour - Seriously, go check out his work!
  • Wikipedia
  • http://blog.apigee.com/detail/restful_api_design/
  • http://blog.nodejitsu.com/a-simple-webservice-in-nodejs
  • https://developers.google.com/+/
  • http://code.google.com/apis/gadgets/