Google’s Mission
As you may know, Google’s mission is to organize the world’s information and make it universally accessible and useful. This article discusses how Google is doing just that by providing easy to use JavaScript-based APIs that allow a wide range of web developers, from experts to casual bloggers, to integrate rich and compelling Google provided search and feed data seamlessly into their web pages. More specifically, this article reviews the overall architecture of Google’s AJAX Search and AJAX Feed APIs and shows how to use the technologies they provide. As you’ll see with this article, integrating cool search and Internet feed technologies ranging from traditional web searches to compelling multimedia searches is actually very easy to do without even requiring a hard core AJAX programming background.
Introducing the Google AJAX APIs: AJAX Search and AJAX Feed
Have you ever wanted to integrate rich, multimedia, search, or feed-based Internet content into your web applications/pages only to realize that creating your own AJAX infrastructure for doing this turned out to be a daunting task? Fortunately, Google provides a solution to this by providing very easy to use JavaScript APIs known as the AJAX Search and AJAX Feed APIs. These APIs are cousins to the popular Google Maps API and are functionally similar in that you can use them to easily insert rich AJAX content into your pages simply by adding small amounts of JavaScript code.
The AJAX Search API allows you to easily integrate some very powerful and diverse Google based search mechanisms or “controls” onto a Web page with relatively minimal coding. These include:
- Web Search: This is a traditional search input field where, when a query is entered, a series of text search results appear on the page.
- Local Search: With Local Search, a Google Map is mashed together with a search input field and the search results are based on a specific location.
- Video Search: The AJAX Video Search provides the ability to offer compelling video search along with accompanying video based search results.
Other search controls also included in the AJAX Search API are Google News Search, Blog Search, and Book Search; each offer enhanced and specialized search capabilities.
The AJAX Feed API is an Internet feed-based technology that allows web developers to pull down any RSS or Atom feed and integrate it into their web pages purely via JavaScript, all without requiring access to a server. In addition to raw data access to Internet feeds, Google also provides custom solutions built on top of the feed mechanism and offers rich feed-based solutions including a feed driven slideshow control.
Getting Started with the Google AJAX APIs
To get a feel for how to use Google’s AJAX APIs, you’ll review a simple “HelloWorld” AJAX Search application that integrates Google’s powerful search mechanism into a custom web page.
A HelloWorld AJAX Search Example
Getting started with an AJAX Search example is a two-step process. The first step, as with any of Google’s AJAX APIs, involves generating an API key for your usage of the API. This can be accomplished by going to Google’s developer web site, http://code.google.com, and generating an API key. A Google API key allows you to use the AJAX APIs on a particular web site or domain.
After generating a key, you then can create your own HelloWorld example with the AJAX API. Fortunately, this is just a matter of copying and pasting a provide example from http://code.google.com.
Here is the core part of a HelloWorld example provided in the AJAX Search Web site at code.google.com in the samples section (http://code.google.com/apis/ajaxsearch/samples.html/):
<html> <head> <script src="www.google.com/uds/api?file=uds.js&v=1.0 &key=YOUR-KEY" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ function onLoad() { // Create a search control var searchControl = new GSearchControl(); // Add in a full set of searchers var localSearch = new GlocalSearch(); searchControl.addSearcher(localSearch); searchControl.addSearcher(new GwebSearch()); searchControl.addSearcher(new GvideoSearch()); searchControl.addSearcher(new GblogSearch()); searchControl.addSearcher(new GnewsSearch()); searchControl.addSearcher(new GbookSearch()); // Set the Local Search center point localSearch.setCenterPoint("New York, NY"); // tell the searcher to draw itself and tell it where to attach searchControl.draw(document.getElementById("searchcontrol")); // execute an inital search searchControl.execute("VW Beetle"); } GSearch.setOnLoadCallback(onLoad); //]]> </script> </head> <body> <div id="searchcontrol">Loading</div> </body> </html
In reviewing this code example, you first note that an external JavaScript file, uds.js, is downloaded into the page. The uds.js file provides some of the behind-the-scenes plumbing for enabling the search mechanism into your page. Notice that, to download this file, an API key is passed as an argument to the host providing the JavaScript file.
Note: In the above example, YOUR-KEY would be replaced with the one generated for you. |
In addition to including the core uds.js file into the page, an additional bit of custom JavaScript is needed to specify some specifics such as what type of search mechanism and some additional settings such as how to render itself on the page.
Notice the first line of code:
var searchControl = new GSearchControl();
It first creates a new base GSearchControl class. The next bit of code adds specific searcher options to the base control. As you can see, searchers for Local, Web, Video, Blog, News, and Book are added to the search control by using:
var localSearch = new GlocalSearch(); searchControl.addSearcher(localSearch); searchControl.addSearcher(new GwebSearch()); searchControl.addSearcher(new GvideoSearch()); searchControl.addSearcher(new GblogSearch()); searchControl.addSearcher(new GnewsSearch()); searchControl.addSearcher(new GbookSearch());
And finally, to execute an initial search as the page is loaded, the line:
GSearch.setOnLoadCallback(onLoad);
is used to execute the “onLoad( )” function that both initializes the search controls and executes an initial search using:
searchControl.execute("VW Beetle");
This results in the page rendering with an initial set of search results.
Figure 1: A HelloWorld AJAX Search
Notice the search results are nicely formatted with collapsible sections. There are also clickable icons that allow you to alter the appearance and behavior of the results.
Figure 2: AJAX Search customizable formatted results
The results number icon, , allows you to define how many results you want displayed ranging from 1, 4 to 8. The search options icon,
, allows you to specify further search or reporting options such as changing the local search location, or how to sort the results, such as by date. The “X” to the right of the main search button allows for cancelling a search before it completes.
A HelloWorld AJAX Feed Example
In a similarly simple fashion, learning how to use the AJAX Feed API is best done using a HelloWorld type example. As with the AJAX Search API, there also exists plenty of code examples at the AJAX Feed API homepage at http://code.google.com/apis/ajaxfeeds/. Here is a simple example using the AJAX Feed API’s FeedControl.
<html> <head> <script type="text/javascript" src="http://www.google.com/ jsapi?key=YOUR-KEY"></script> <script type="text/javascript"> google.load("feeds", "1"); function initialize() { var feedControl = new google.feeds.FeedControl(); feedControl.addFeed("http://www.digg.com/rss/index.xml", "Digg"); feedControl.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch"); feedControl.draw(document.getElementById("feedControl")); } google.setOnLoadCallback(initialize); </script> </head> <body> <div id="feedControl">Loading</div> </body> </html>
As you can see, using the AJAX Feed FeedControl to pull down and display Internet feeds is done in a very similar manner as adding searchers to the AJAX Search control. When rendered on a web page, the AJAX Feed FeedControl renders feed items onto a page in a nicely formatted manner. If more than one feed is specified, their items can be stacked (as shown below) or placed in separate tabbed pages.
Figure 3: The AJAX Feed API in action
Before diving into more examples of how to use these rich AJAX solutions, it’s helpful to first review the underlying architecture of Google’s AJAX APIs that make these solutions possible.
The Architecture of Google’s AJAX APIs
In short, the Google AJAX APIs serve as an enhanced conduit to several of Google’s most popular hosted services. The hosted services such as Google Search or Google Maps can be accessed directly, but with AJAX APIs comes the ability to integrate these hosted services into anyone’s custom web pages.
Figure 4: The AJAX APIs architecture at a glance
The way the AJAX APIs work is by allowing any web page that is hosted on the Internet access to Google search (or feed) data through JavaScript code. The core JavaScript code that fetches the search or feed data can be as simple as Search.execute( ) or Feed.load( ). As the request is made to Google’s worldwide servers, a response of either Search data or prepared AJAX Feed data is streamed back to the Web page in either JSON (JavaScript Object Notation) or XML formats. Parsing of this data can either be done manually or automatically by using one of the provided UI controls that are built upon the lower level AJAX APIs. In fact, the AJAX APIs in general are architected in a layered fashion.
The AJAX APIs Layered Architecture
The AJAX APIs are designed in a layered architecture that provides different functionality at different levels. If someone wants to use the APIs at its lowest, or “raw,” level, one can do so, albeit providing they are comfortable with more advanced JavaScript and AJAX programming. People less comfortable with JavaScript programming, or who don’t want to re-invent the wheel, can use the APIs at higher levels. In short, the AJAX APIs offer programming solutions to a variety of developers based on their background because of its layered approach.
Here is how the AJAX APIs along with their respective UI controls are layered:
Figure 5: The AJAX APIs Layered architecture at a glance
As you can see in Figure 5, The AJAX APIs have a layered architecture. Here’s a more thorough description of each layer starting at the lowest level:
- Raw Data Access Layer: This layer provides a very low-level access to the AJAX Search and Feed services from Google’s servers. If you operate at this level, you have full control of how to display the data as it comes down from Google’s servers to your page. In short, it’s Google’s data, but your User Interface. Accessing the AJAX Search and Feed data provided by Google’s services involves true AJAX programming as JavaScript developer’s have to be skilled with technologies such as JSON as well as manipulating the DOM (The Document Object Model).
- Base UI Layer: The base UI layer provides some very basic User Interface technology out of the box. At this layer, one doesn’t need to resort to low-level JSON parsing or DOM manipulation. He can simply use some basic User Interface controls such as the FeedControl as is and let it do the work of communicating back to the server to pull down data and display it.
- Advanced UI Layer: The Advanced UI Layer provides the highest level of sophistication and specialization from the AJAX APIs. At this level exist UI controls that are specialized to provide a specific solutions such as a Google Maps and Search mashup, a Video Bar, or for the Feed API, a SlideShow, or Itunes Bar.
The Raw Data Access Layer
A good demonstration of programming at the Raw Data Access Layer can be shown with the AJAX Feed API. Instead of using the powerful FeedControl, it is possible to to extract the Feed data directly and write your own code to display the fields. This is useful if you want be in 100% full control of how your data renders. In this Raw Data Access Layer version of a AJAX Feed Hello World example, you see how to pull down a feed from digg.com, extract the title element, and display it onto the page using DOM programming.
<html> <head> <script type="text/javascript" src="http://www.google.com/ jsapi?key=YOUR_KEY_HERE"></script> <script type="text/javascript"> google.load("feeds", "1"); function initialize() { var feed = new google.feeds.Feed("http://www.digg.com/ rss/index.xml"); feed.setNumEntries(7); feed.load(function(result) { if (!result.error) { var container = document.getElementById("feed"); for (var i = 0; i < result.feed.entries.length; i++) { var entry = result.feed.entries[i]; var div = document.createElement("div"); div.appendChild(document.createTextNode (entry.title)); container.appendChild(div); } } }); } google.setOnLoadCallback(initialize); </script> </head> <body> <div id="feed"></div> </body> </html>
Note: It’s important to remember that this is an example of accessing the raw data at its lowest level. As shown elsewhere in this article, the AJAX Feed FeedControl widget, which is not used in the previous code example, actually performs the task of rendering the feed data into the page, but more on that later… |
A quick inspection of the preceding code shows how the feed is loaded and a callback function is registered to handle the incoming feed results. The function iterates through the feed entries and, for each entry title, it appends the text of the title to a <div> container. Incidentally, the entry.title element is one of several elements made available via the canonicalized or unified JSON output of the AJAX Feed API. Why is it unified? For the simple reason that the AJAX Feed API serves several versions of both the RSS and Atom feed formats and with a unified version, programmers can just use a single set of elements and be guaranteed that it will work for multiple feed types. This allows for extreme flexibility when pulling down feed data of different formats.
JSON and XML outputs for the Feed API
In addition to the canonicalized JSON format, the AJAX Feed API also provides an XML data output as well as a mixed XML and JSON output. The XML output allows programmers to access any element of the feed even if it doesn’t fall into the canonicalized JSON output. An example of this occurs when dealing with GEORSS feeds where the latitude and longitude elements of the feed are not currently available from the JSON output. In this case, a mixed mode output is used; it allows you to extract from the JSON output as well as any extra elements that are only provided in the raw XML output directly.
The Base UI Layer
Returning back to the overall architecture of the AJAX APIs, recall that above the Raw Data Access Layer lies below the Base UI Layer. With the Base UI Layer comes helpful code to display data without having to do low level DOM programming.
The GSearchControl
The other Base UI layer control from the AJAX APIs is the GSearchControl. As you’ve seen earlier in the article, this control provides a simple solution to the overall task of displaying the results of an AJAX Search. Extending upon the GSearchControl example from before, this example shows how to specify the Tabbed Mode rendering option as well for AJAX Search.
...function OnLoad() { // create a search control sc = new GSearchControl(); sc.addSearcher(new GwebSearch()); sc.addSearcher(new GblogSearch()); sc.addSearcher(new GnewsSearch()); sc.addSearcher(new GbookSearch()); // set up for tabbed mode var drawOpt = new GdrawOptions(); drawOpt.setDrawMode( GSearchControl.DRAW_MODE_TABBED); // bind to page sc.draw(scDiv, drawOpt); } ...
And here is how the preceding code is rendered:
Figure 6: The GSearchControl with several searchers rendered in Tabbed Mode
In a similar manner, GSearchControl‘s appearance is governed by a similar set of base CSS classes located here: http://www.google.com/uds/css/gsearch.css and one can override these by adding classes to the HTML page that contains GSearchControl. The following CSS code would suppress the snippet portion of the AJAX Search results.
#mycontrol .gs-webResult .gs-snippet { display : none; }
The Advanced UI Layer
In addition to the base controls offered by the AJAX APIs, there is a higher level collection of controls that provide more specialized output such as a video bar, blog bar, or a feed-based slideshow. These more advanced control are extensions upon the Base UI Layer and are appropriately grouped in the Advanced UI Layer. One of the cool things about these advanced UI controls is that they easily can be downloaded and customized or extended upon. Several even have accompanying wizards that help generate custom usage code for the end user. Some of these most compelling controls include a video bar that shows playable videos based on a search query in a bar, a news bar with similar behavior but for news searches as well as a slideshow that displays images from Internet feeds.
Similar to the Base UI controls, minimal JavaScript code is needed for them to run on a page. For example, the code below is used to place a video bar on a page:
function LoadVideoBar() { var options = { largeResultSet : false, autoExecuteList : { executeList : ["Kelly Clarkson",...] } }; barDiv = document.getElementById("bar"); playDiv = document.getElementById("player"); new GSvideoBar(barDiv, playDiv, options); } ... <div id="player">Loading...</div> <div id="bar">Loading...</div>
As you can see, loading a video bar (GSVideoBar) is simply a matter of setting some options such as the initial search query and then creating a new GSVideoBar object with these options. Also notice that there are two elements for a video bar, a player and the accompanying video bar itself.
In the browser, the video bar can appear in either vertical or horizontal orientations. Here is how the horizontal video bar appears:
Figure 7: The AJAX Search Video Bar
In addition to the Advanced UI Layer controls for AJAX Search, the AJAX Feed API also has advanced controls such as the AJAX Feed SlideShow. In total, the AJAX APIs have over seven different specialized advanced UI controls and counting for different types of applications including news bars, local search, as well as controls that work in Blogger.
Figure 8: A Collection of Advanced UI Controls
AJAX API Wizards
If you’re not into JavaScript coding but are a master at copying and pasting, the AJAX Search APIs provides a solution for you! With AJAX Search’s wizards you can generate made-to-order code simply by filling out a form!
Figure 9: The AJAX Search Code Generating Wizards
Summary
As you can see, the Google AJAX Search and APIs offer a whole host of fun and rich technology that can easily be integrated into your own web environment. Whether your are a diehard AJAX programmer perfectly comfortable manipulating DOM elements, or simply just want to add some neat content to your Blog, the Google AJAX APIs have a solution for you. For more information on the Google AJAX APIs, check out Google’s API technology web site at: http://code.google.com or more specifically, for the AJAX Search API see: http://code.google.com/apis/ajaxsearch/ and for the AJAX Feed API, see: http://code.google.com/apis/ajaxfeeds/. You’ll see plenty of documentation, samples, and of course the code generation wizards at these site. Happy AJAX programming!
About the Author
Chris Schalk is a tech lead in the API developer evangelism group and works to promote Google’s AJAXian APIs and technologies. Before joining Google, Chris was a Principal Product Manager and technology evangelist at Oracle in the Java development tools group. Chris also recently co-authored the widely popular JSF book: JavaServer Faces, The Complete Reference published through McGraw-Hill-Osborne. Chris has also published many articles on Java and web development in many publications and web sites, including Oracle magazine, Java Developer’s Journal, JavaLobby.org, TheServerSide.com, and Developer.com.