The RESTful data APIs are the core of the Google+ platform. These APIs provide read access to public fields on profiles, activities, and comments. Access to private data, specifically a user’s identity on Google+, is controlled by OAuth 2.0, and API quotas are controlled by API keys.
The easiest way to gain an understanding of the public data APIs is to see them in action.
Baking Disasters is pretty cool, but do you know what would make it cooler? Comments would. Discussion can bring a blog to life, but sadly, they come at a cost. Not only do you need to worry about spam comments, but you also have to expose potentially sensitive software to the outside world.
Fortunately, the Google+ public data APIs expose the comments on your public activities. Since you’re already sharing your blog posts to Google+, you can use JavaScript to render the comments from the activity right in the blog entry. Not only does this prequalify users to reduce spam, but it also allows you to keep Baking Disasters static HTML.
Before you start coding, spend some time to become comfortable with how the APIs behave. The API Explorer from the introduction chapter is perfect for this. You can find it here: https://developers.google.com/apis-explorer/#s/plus/v1/.
Use the API Explorer to trace the same steps that the comments plugin will follow.
Scan through the available methods in the API Explorer. The
comments.list
method, pictured in
Figure 3-1, looks perfect. Unfortunately, it requires
an activity ID.
Just above the comments.list
method there is an activities.list
method, pictured in Figure 3-2. This lists recent activities and provides their
IDs.
Listing activities requires one more piece of information:
your userId
. The easiest way to
determine your userId
is to copy
it from your Google+ profile URL, as shown in Figure 3-3. This technique works for both Google+ pages and
user profiles.
Paste your userId
into the
activities.list
form and select
the public
collection. Click
execute to trigger the API call. The JSON response body renders in
the history pane at the bottom of the page, as shown in Figure 3-4.
The response 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, as shown in Figure 3-5. Copy the ID for your most recent entry.
Switch to the comments.list
method and supply the activity ID that you just copied, as shown in
Figure 3-6.
Execute this request. The history pane now contains the comments associated with that activity, as shown in Figure 3-7.
This flow that you just traced in the API Explorer is a reasonable flow for a comments plugin. Manually discover the activity ID for your activity on Google+, and use JavaScript to fetch and render the comments associated with it.
Google probably provides an official client library for your favorite language. These client libraries make development against APIs faster by taking care of low-level tasks and providing you with an interface that embraces the development style of your language. You’ll save yourself a lot of time by using the official client libraries.
The current library offering is shown in Table 3-1.
Table 3-1. Links to the Google API Client Libraries
Language | Project |
---|---|
.NET | |
Go | |
Google Web Toolkit | |
Java | |
JavaScript | |
Objective C | |
PHP | |
Python | |
Ruby |
The comments plugin will use the JavaScript client library.
Before you can use the APIs to access public data you must register your application on the API console. This is how Google identifies the source of API calls and provision quota.
Navigate to the API Console on Google Developers: https://developers.google.com/console. Create a new project using the project drop down menu as shown in Figure 3-8.
Click “Services” in the API Console menu and toggle the Google+ API to “on,” as shown in Figure 3-9.
Click “API Access” in the API Console menu to access the API key for your application, as shown in Figure 3-10.
Just like the official Google+ plugins, the comments plugin
renders comments within a div
identified by a special class. It uses JavaScript to replace this
placeholder div
with the comments for
that entry. Example 3-1 shows an example of a div
element that the comments plugin will look
for:
Example 3-1. The div element that will be replaced by a list of comments
<div
class=
"g-comments-for z13zevjymuuge1zvl23lyv3a2n3owdxxd04"
></div>
Create a new JavaScript file named pluscomments.js
and include it into each blog
entry. Edit the JavaScript file and create a namespace for your
functions, and create a variable for your API key, as shown in Example 3-2.
Example 3-2. The comment plugin namespaced and configured with an API key
var
commentr
=
commentr
||
{};
var
apiKey
=
"AIzaSyA-H-eBvhWOyzjIJ2bWeaf1XAn855s8IRN"
;
To make calls you need an instance of the JavaScript API client. Load the client library with the name and version of the API and tell it your API key, as shown in Example 3-3. This function is automatically called by the JavaScript client library when it has finished loading and hence must reside in the global namespace.
Example 3-3. Bootstrapping the JavaScript API client library
function
commentrLoad
()
{
gapi
.
client
.
load
(
'plus'
,
'v1'
,
commentr
.
go
);
gapi
.
client
.
setApiKey
(
apiKey
);
}
Next, find all of the g-comment-for
divs and extract the activity
ID, as shown in Example 3-4.
Example 3-4. Search the DOM for all of the g-comments-for elements
// 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
);
}
}
Take the resulting collection of activity IDs and list the comments for each one. Each API response triggers the same callback function. Example 3-5 shows how to do this.
Example 3-5. Extract the appropriate activity ID, fetch its comments and insert them into the appropriate g-comments-for element
commentr.fetchComments = function(activityId) {var request = gapi.client.plus.comments.list({ 'activityId': activityId, 'maxResults': '100' }); request.execute(commentr.parseComments);
} commentr.parseComments = function(responseJson) { var activity = responseJson.items[0].inReplyTo[0]; var comments = responseJson.items; 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; 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>"; }
Finally, source the JavaScript client library and configure it to
load the comments plugin. Source
it in the entry pages and specify the init
function to the onload
parameter. Example 3-6
shows the macaron entry header with the client library added:
Example 3-6. Load the JavaScript API client library and execute the comment plugin’s load function
<head>
<title>
Baking Disasters</title>
<link
rel=
"stylesheet"
href=
"style.css"
/>
<link
rel=
"shortcut icon"
href=
"images/logo_favicon.png"
/>
<script
src=
"pluscomments.js"
></script>
<script
src=
"https://apis.google.com/js/client.js?onload=commentrLoad"
>
</script>
</head>
That was pretty easy, wasn’t it? Now let’s see the comments plugin in action.
Use the API Explorer to discover the activity ID of your most
recently public entry. For example, z133jnaofxb5wzfnx23lyv3a2z3owdxxd04
. Return to
that entry and add the placeholder div
, such as the one in Example 3-7, that becomes the list of comments.
Example 3-7. A div element configured with an activity ID
<div
class=
"g-comments-for z133jnaofxb5wzfnx23lyv3a2n3owdxxd04"
></div>
Reload the page to see the rendered comments. It should look similar to Figure 3-11.