Google Feed API

Google Feed API Developer's Guide

With the Google Feed API, you can download any public Atom or RSS feed using only JavaScript, so you can easily mash up feeds with your content and other APIs like the Google Maps API.

Table of Contents

  1. Introduction
    1. Scope
    2. Browser compatibility
    3. Audience
    4. The "Hello World" of Feed
  2. Getting Started
    1. Load the JavaScript API
  3. Using the API
    1. Building a basic application
      1. Specifying the feed URL
      2. Loading the feed
      3. Calling the onLoad handler
    2. Configuring additional methods
      1. Setting the number of feed entries
      2. Setting the feed format
      3. Loading historical entries
      4. Returning nodes by element ID
      5. Matching feeds to a query
    3. Calling the onLoad handler
  1. Result formats
    1. Basic
    2. JSON
    3. XML
    4. Mixed
    5. FindResult
  2. Troubleshooting

Introduction

This developer's guide provides a basic model for using the Google Feed API, along with granular explanations of the API's configurable JavaScript components. You can use this guide to enable Feed on your webpage or application.

Scope

This document describes how to use the functions and properties specific to the Feed API.

Browser compatibility

The Feed API supports Firefox 1.5+, IE6+, Safari, Opera 9+, and Chrome.

Audience

This documentation is intended for developers who wish to add Google Feed functionality to their pages or applications.

The "Hello World" of Feed

The following example creates loads a feed, processes results, and displays feed entries in a div.

<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">

    google.load("feeds", "1");

    function initialize() {
      var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
      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>

Visit the code playground to play with this sample.

Getting Started

Loading the JavaScript API

To begin using the Feed API, include the following script in the header of your web page.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Next, load the Feed API with google.load(module, version, package), where:

  • module calls the specific API module you wish to use on your page (in this case, elements).
  • version is the version number of the module you wish to load (in this case, 1).
  • package specifies the specific elements package you wish to load, in this case Feed.
<script type="text/javascript">
  google.load("feeds", "1");
</script>

You can find out more about google.load in the Google Loader developer's guide.

When we do a significant update to the API, we will increase the version number and post a notice on the API discussion group. Take note of any required code changes when this occurs, and update your URLs to the new version when they are compliant.

The Google API team will also periodically update the API with recent bug fixes and performance enhancements without requiring a version update. For the most part, these fixes should remain transparent to you, but we may inadvertently break some API clients. Please use the API discussion group to report such issues.

Using the API

The following sections demonstrate how to incorporate the Google Feed API into your web page or application. Using this API requires an asynchronous call to a server, so you need a callback to exchange the data.

Building a basic application

The following methods provide the basic functionality of the API to retrieve a feed and display feed entries to the user. You can extend this basic functionality with the additional methods described later in this manual.

Specifying the feed URL

Instances of the google.feeds.Feed(url) class can download a single feed, where url provides the URL for the desired feed.

Basic applications load the feed using the .load() method. Processing results from this API requires an asynchronous callback to the Google server; therefore, you need to set a callback function (google.setOnLoadCallback) to process the feed data when the page loads.

You can call google.feeds.Feed() as follows:

var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");

You can further manipulate the feed using the methods described in this section.

Loading a feed

.load(callback) downloads the feed specified in the constructor from Google's servers and calls the given callback when the download completes. The given function provides a a single feed result argument representing the result of the feed download.

.load() has no return value.

The following code snippet demonstrates how to use this method in conjunction with the google.feeds.Feed(url) constructor.

function initialize() {
  var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
  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);
        }
      }
    });
  }

Calling the onLoad handler

.setOnLoadCallback(callback) is a static function that registers the specified handler function to be called once the page containing this call loads, where callback is a required function called when the containing document is loaded and the API is ready for use (e.g., after onLoad). This function is implemented on the google namespace (i.e., google.setOnLoadCallback(callback);)

.setOnLoadCallback() has no return value.

Note: Previous documentation recommended that you use the body element's onload attribute (<body onload="OnLoad()">). While this is a fine way to go when you are in complete control of the page and all code loaded by the page, this approach can cause problems with some runtimes that destroy your body.onload handler. setOnLoadCallback() does not have these problems, and therefore is the recommended method of registering a callback that calls your code when the API is fully loaded and ready for use.

The following code snippet demonstrates the use of this method:

google.setOnLoadCallback(handler);

Configuring additional methods

In addition to the namespace-specific methods described above, the Feed API also provides the following, global, methods built on the google.feeds namespace.

Setting the number of feed entries

.setNumEntries(num) sets the number of feed entries loaded by this feed to num. By default, the Feed class loads four entries.

.setNumEntries() has no return value.

The following code snippet demonstrates how to retrieve two feed entries:

var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.setNumEntries(2);

Setting the feed format

.setResultFormat(format) sets the result format to one of google.feeds.Feed.JSON_FORMAT, google.feeds.Feed.XML_FORMAT, or google.feeds.Feed.MIXED FORMAT. By default, the Feed class uses the JSON format.

.setResultFormat() has no return value.

The following code snippet demonstrates how to specify results in XML format:

var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.setResultFormat(google.feeds.Feed.XML_FORMAT);

You can also play with this sample in the code playground.

Loading historical entries

.includeHistoricalEntries() returns feed entries stored by Google that are no longer in the feed XML. For example, if a feed only keeps the most recent four entries in its XML, you can use .includeHistoricalEntries() to include more than four.

If used in conjunction with a PubSubHubbub-enabled feed, this method allows you to load feed updates when the page loads, within a few minutes of publication.

Since including historical entries increases the number of returned feed entries, most developers combine this method with setNumEntries.

.includeHistoricalEntries() has no arguments and no return value.

The following code snipppet demonstrates how to load historical entries:

var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.includeHistoricalEntries();

You can also play with this sample in the code playground.

Returning nodes by element ID

.getElementsByTagNameNS(node, ns, localName) is a cross-browser implementation of the DOM function getElementsByTagNameNS, where:

  • node supplies a node from the XML DOM to search within.
  • ns supplies the namespace URI. The value "*" matches all tags.
  • localName supplies the tag name for the search.

.getElementsByTagNameNS() returns a NodeList of all the elements with a given local name and namespace URI. The elements are returned in the order in which they are encountered in a preorder traversal of the document tree.

Matching feeds to a query

google.feeds.findFeeds(query, callback) is a global method that returns a list of feeds that match the given query, where:

  • query supplies the search query for the list of feeds.
  • callback supplies the callback function that processes the result object asynchronously.

google.feeds.findFeeds() has no return value.

The following sample demonstrates the use of this method. You can also play with this sample in the code playground.

/*
*  How to find a feed based on a query.
*/

google.load("feeds", "1");

function OnLoad() {
  // Query for president feeds on cnn.com
  var query = 'site:cnn.com president';
  google.feeds.findFeeds(query, findDone);
}

function findDone(result) {
  // Make sure we didn't get an error.
  if (!result.error) {
    // Get content div
    var content = document.getElementById('content');
    var html = '';

    // Loop through the results and print out the title of the feed and link to
    // the url.
    for (var i = 0; i < result.entries.length; i++) {
      var entry = result.entries[i];
      html += '<p><a href="/feed/v1/' + entry.url + '">' + entry.title + '</a></p>';
    }
    content.innerHTML = html;
  }
}

google.setOnLoadCallback(OnLoad);

Result objects

Basic

The .load() method calls the function argument with a single result when the feed download completes. The result has the following structure:

  • <root>
    • error?
      Present if there was an error loading the feed.
    • xmlDocument?
      The feed XML document. Present for the XML_FORMAT and MIXED_FORMAT result formats. See the XML documentation below.
    • feed?
      The JSON representation of the feed. Present for the JSON_FORMAT and MIXED_FORMAT result formats. See the JSON documentation below.

JSON

If you request the google.feeds.Feed.JSON_FORMAT result format, the feed attribute appears in the feed result. It corresponds to the json value for the output argument in JSON. The feed attribute has the following structure:

  • feed
    • feedUrl
      The URL for the feed.

      Note: This API uses URL normalization to standardize feed URLs. Therefore, the API does not always return the same URL that you supplied. The context parameter allows you to distinguish between multiple feed load requests.

    • title
      The feed title. Corresponds to the <title> element in Atom and the <title> element in RSS.
    • link
      The URL for the HTML version of the feed. Corresponds to the <link> element in Atom and the <link> element in RSS.
    • description
      The feed description. Corresponds to the <subtitle> element in Atom and the <description> element in RSS.
    • author
      The feed author. Corresponds to the <name> element for the author in Atom.
    • entries[]
      A list of all of the entries in the feed. Corresponds to the <entry> element in Atom and the <item> element in RSS.
      • mediaGroup
        A container for Media RSS feed results. All result properties nested under mediaGroups correspond exactly as documented in the Media RSS Specification. Media RSS is available only for feed entries newer than February 1st, 2010. Please refer to that specification for detailed information about Media RSS fields.
      • title
        The entry title. Corresponds to the <title> element in Atom and the <title> element in RSS.
      • link
        The URL for the HTML version of the entry. Corresponds to the <link> element in Atom and the <link> element in RSS.
      • content
        The body of this entry, inlcuding HTML tags. Since this value can contain HTML tags, you should display this value using elem.innerHTML = entry.content (as opposed to using document.createTextNode). Corresponds to the <content> or <summary> elements in Atom and the <description> element in RSS.
      • contentSnippet
        A snippet (< 120 characters) version of the content attribute. The snippet does not contain any HTML tags.
      • publishedDate
        The string date on which the entry was published of the form "13 Apr 2007 12:40:07 -0700". You can parse the date with new Date(entry.publishedDate). Corresponds to the <published> element in Atom and the <pubDate> element in RSS.
      • categories[]
        A list of string tags for the entry. Corresponds to the term attribute for the <category> element in Atom and the <category> element in RSS.

XML

If you request the google.feeds.Feed.XML_FORMAT result format, the API places the xmlDocument attribute in the feed result. This attribute is the fully parsed XML Document node for the feed. It corresponds to the xml value for the output argument in JSON. You can access the document using the XML functionality built into browsers (e.g., getElementsByTagName).

Mixed

If you request the google.feeds.Feed.MIXED_FORMAT result format, the API places both the feed JSON attribute and the xmlDocument XML DOM attribute in the feed result. It corresponds to the json_xml value for the output argument in JSON. See the JSON result format and XML result format for details.

In addition to those attributes, every entry in the JSON results array contains an additional xmlNode property. That property is a pointer to the XML Element representing that entry in the feed XML document. For an ATOM feed, xmlNode points to the <entry> element for the entry. For an RSS feed, xmlNode points to the <item> element for the entry.

FindResult

The findFeeds() method calls the callback function argument with a single result when the feed query completes. The result has the following structure:

  • <root>
    • error?
      Present if there was an error loading the feed.
    • entries[]
      A list typically containing up to ten feeds that matched the given query string.
      • title
        The feed title.
      • link
        The URL for the HTML version of the feed.
      • contentSnippet
        A snippet (< 120 characters) version of the content.
      • url
        The URL for the actual feed.

Troubleshooting

If you encounter problems:

  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. Google Chrome has a full set of developer tools. In Firefox, you can use the JavaScript console or the Firebug. In IE, you can use the Microsoft Script Debugger.
  • Search the discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.