My favorites | English | Sign in

Google AJAX Feed API

Class Reference

Google is developing a new version of the Feed API with the ability to push feed updates via pubsubhubbub. For more information, please visit the Feed API v2 with Push documentation.

Table of Contents

Classes

class google.feeds.Feed

Instances of the google.feeds.Feed class can download a single feed URL.

Constructor

Constructor Description
Feed(url) Creates a new Feed instance that can download the given feed URL.

Methods

Method Return Type Description
load(callbackFunction)
None
Downloads this feed from Google's servers, calling the given callbackFunction when the download completes. The given function is called with a single feed result argument representing the result of the feed download.

setNumEntries(num)
None
Sets the number of feed entries loaded by this feed to num. By default, the Feed class loads 4 entries.
setResultFormat(format)
None
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.
includeHistoricalEntries()
None
By default, when a feed is loaded, the system returns a cached copy of the specified feed that is 100% in sync with the feed contents at the time that it was cached. By calling this method, you can instruct the system to return any additional historical entries that it might have in its cache.

class google.feeds.FeedControl

Instances of the google.feeds.FeedControl class are designed to download and display multiple feeds. This class is very similar to the AJAX Search API's Search Control layer GSearchControl.

Constructor

Constructor Description
FeedControl() Creates a new FeedControl instance. After creating the control, the addFeed() method is called once for each feed that you want to download and display, and then the draw() method is called to begin the download sequence and draw the results onto your page.

Methods

Method Return Type Description
addFeed(url, label)
None
The feed specified by url is added to the control and is associated with a section whose header title is label. Note: the feed is not actually loaded until the draw() method is called. The feedcontrol.html sample demonstrates the use of this method.
draw(element, opt_options?)
None
All of the feeds previously added to the control are loaded and as they load they are added to the page. The element argument supplies the DOM Node that contains the resulting entries.

The optional opt_options argument supplies options that control how the control displays the results. This argument is an anonymous object which currently supports a single property called drawMode which can have a value of either google.feeds.FeedControl.DRAW_MODE_TABBED or google.feeds.FeedControl.DRAW_MODE_LINEAR. For example, the following code fragment demonstrates how to request that the feed control draws the feeds using a tabbed style. The tabbed.html sample demonstrates this.

feedControl.draw(
  document.getElementById("feedControl"),
  {
    drawMode : google.feeds.FeedControl.DRAW_MODE_TABBED
  });
    
The default drawMode is linear mode e.g., google.feeds.FeedControl.DRAW_MODE_LINEAR.
setNumEntries(num)
None
Sets the number of feed entries loaded for each feed added to this control to num. By default, the FeedControl class loads 4 entries from each feed.
setLinkTarget(linkTarget)
None
The control generates default HTML for each entry that it displays. The HTML consists of the hyper-linked entry title, the author and published date, and the entry's content snippet. This method allows the caller to specify the target of the hyper-linked title. Valid values include:
  • google.feeds.LINK_TARGET_BLANK - links will open in a new window
  • google.feeds.LINK_TARGET_SELF - links will open in the current window
  • google.feeds.LINK_TARGET_TOP - links will open in the topmost frame
  • google.feeds.LINK_TARGET_PARENT - links will open in either the topmost frame, or replace the current frame.
  • anything-else - the value of target in the resulting anchor element is set to linkTarget
The default value of this setting for the control is google.feeds.LINK_TARGET_SELF.

CSS Structure

The FeedControl emits HTML markup with precise class annotations. These classes are designed to allow you to easily style both the control and the per-entry HTML. If you are skilled in CSS, its relatively easy to style the FeedControl to meet your needs. The key thing to understand is that the base CSS styling is defined in the auto-loaded stylesheet gfeed.css. You can analyze this auto-loaded CSS and then define specific style overrides to suit your needs. The skeleton CSS structure is shown below.

<!-- The Feed Control Class (Note: Linear Mode is Shown) -->
<div class="gfc-control">

  <!-- Per Feed Container -->
  <div class="gfc-resultsRoot">

    <!-- Per Feed Header -->
    <!-- .gfc-title holds Feed's Label -->
    <div class="gfc-resultsHeader">
      <div class="gfc-title"></div>
    </div>

    <!-- Collection of Entries -->
    <div class="gfc-results">

      <!-- One .gfc-result per entry -->
      <div class="gfc-result">

        <!-- One .gf-result per entry -->
        <div class="gf-result">

          <!-- Hyperlinked Entry Title -->
          <div class="gf-title">
            <a class="gf-title"></a>
          </div>

          <!-- Author (Only if entry.author is present -->
          <div class="gf-author"></div>

          <!-- Published Date (Only if entry.publishedDate is present -->
          <div class="gf-relativePublishedDate"></div>

          <!-- Snippet entry.contentSnippet -->
          <div class="gf-snippet"></div>

        </div>
      </div>
      ...
      <div class="gfc-result"></div>
    </div>
  </div>
  ...
  <div class="gfc-resultsRoot"></div>

</div>

In order to help point you in the right direction, we offer the sidebar.html sample. This very simple sample uses some very simple style rules to supress the display of several properties, change some of the default margins, and adjust the font sizes and width. The net result is a very compact form thats perfect for displaying a blogroll style set of links in a typical sidebar. The key pieces of styling are:

<style type="text/css">
  /**
   * Set a very small font size for the control and constrain
   * it's width to 225px
   *
   * Note: the page has a single FeedControl that
   * is drawn in the <div> element whose id is "feedControl".
   */
  #feedControl {
    font-size: 10px;
    width : 225px;
  }

  /**
   * Suppress everything except for title
   */
  #feedControl .gf-snippet,
  #feedControl .gf-author,
  #feedControl .gf-spacer,
  #feedControl .gf-relativePublishedDate {
    display : none;
  }

  /**
   * 1em Padding at the bottom of each collection of entries
   */
  #feedControl .gfc-results {
    padding-bottom : 1em;
  }

  /**
   * no padding between entries
   */
  #feedControl .gfc-result {
    margin-bottom : 0px;
  }

  /**
   * Use a larger font size for section titles
   */
  #feedControl .gfc-resultsHeader .gfc-title {
    font-size : 110%;
  }
</style>

Global Methods

Method Return Type Description
google.feeds.findFeeds(query, callback)
None
A global method that will return a list of feeds that match the given query. The results are supplied asynchronously to the given callback function as the result object. The Discover Feed Lookup sample demonstrates the use of this method.
google.feeds.lookupFeed(url, callback)
None
A global method that will return the associated feed, if it exists, for a given url. The result is supplied asynchronously to the given callback function as the result object. The Flickr Feed Lookup sample demonstrates the use of this method.
google.feeds.getElementsByTagNameNS(node, ns, localName) NodeList A cross-browser implementation of the DOM function getElementsByTagNameNS. Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree.

Result Format

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 Result Format

If you request the google.feeds.Feed.JSON_FORMAT result format, the feed attribute will be present in the feed result. 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 Result Format

If you request the google.feeds.Feed.XML_FORMAT result format, the xmlDocument attribute will be present in the feed result. The xmlDocument attribute is the fully parsed XML Document node for the feed. You can access the document using the XML functionality built into browsers (e.g., getElementsByTagName).

Mixed Result Format

If you request the google.feeds.Feed.MIXED_FORMAT result format, both the feed JSON attribute and the xmlDocument XML DOM attribute will be present in the feed result. See the JSON documentation and XML documentation above for details.

In addition to those attributes, every entry in the JSON results array will have 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 Format

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.

LookupResult Format

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

  • <root>
    • error?
      Present if there was an error loading the feed
    • url
      The URL for the associated feed if it exists.

Flash and other Non-Javascript Environments

For Flash developers, and those developers that have a need to access the AJAX Feed API from other Non-Javascript environments, the API exposes a simple RESTful interface. In all cases, the method supported is GET and the response format is a JSON encoded result with embedded status codes. Applications that use this interface must abide by all existing terms of use. An area to pay special attention to relates to correctly identifying yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but do not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems. Read more about the usefulness of having an API key

Developers are also encouraged to make use of the userip parameter (see below) to supply the IP address of the end-user on whose behalf you are making the API request. Doing so will help distinguish this legitimate server-side traffic from traffic which doesn't come from an end-user.

Like the core Javascript interface, this interface is exposed through a uniform URL containing a mix of both standard, and method specific CGI arguments. Your application can use an http stack of it's choosing. The only requirement is that you must be able to build up a properly constructed URL with all necessary CGI arguments, that you send an http referer header that accurately identifies your application, and that you are able to process the JSON encoded response.

Standard URL Base Address'

Each Feed API method is accessed through a standard URL. The following table lists the URL used to access each method.

Searcher Base Url
Load Feed http://ajax.googleapis.com/ajax/services/feed/load
Find Feed http://ajax.googleapis.com/ajax/services/feed/find
Lookup Feed http://ajax.googleapis.com/ajax/services/feed/lookup

Standard URL Arguments

Each request contains a mix of standard URL arguments as well as an optional set of method specific arguments. This section describes the standard arguments that are uniform accross all methods and that convey virtually identical semantic information to each method. In some cases, an argument is optional. This is indicated with a ? following the name of the argument. In all cases, the value of a CGI argument must be properly escaped (e.g., via the functional equivalent of Javascript's encodeURIComponent() method).

The following table lists the standard URL arguments. Additional sections, appear below that highlight method specific arguments.

Argument Example Description
q q=Paris%20Hilton This argument supplies the query term passed to the method. For the load and lookup methods, the value of this argument is a property escaped url, e.g., &q;=http%3A%2F%2Fwww.digg.com%2Frss%2Findex.xml. For the find method, the value is a search expression that is used to find a collection of matching feed url's.
v v=1.0 This argument supplies protocol version number. The only valid value at this point in time is 1.0
userip? userip=192.168.0.1 This argument supplies the IP address of the end-user on whose behalf the request is being made. Requests that include it are less likely to be mistaken for abuse. In choosing to utilize this parameter, please be sure that you're in compliance with any local laws, including any laws relating to disclosure of personal information being sent.
hl? hl=fr This optional argument supplies the host language of the application making the request. If this argument is not present then the system will choose a value based on the value of the Accept-Language http header. If this header is not present, a value of en is assumed.
key? key=your-key This optional argument supplies the application's key. If specified, it must be a valid key associated with your site which is validated against the passed referer header. The advantage of supplying a key is so that we can identify and contact you should something go wrong with your application. Without a key, we will still take the same appropriate measures on our side, but we will not be able to contact you. It is definitely best for you to pass a key.
callback? callback=foo This optional argument alters the standard response format. When supplied, instead of producing a simple JSON encoded object, the system produces a Javascript function call response where the value of callback specifies the name of the function called in the response.
callbackFunction({
  "responseData" : {
    "feed" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
})
      
context? context=bar This optional argument is related to the context argument. When both are supplied, the value of context alters the normal response format associated with callback. The new format is:
callbackFunction(
  contextValue,    // the context arg value
  responseObject,  // the method result
  responseStatus,  // 200 on success, non-200 on failure
  errorDetails)    // error string for non-200 response
      

Standard Response Format

As discussed briefly in the previous section, there are two major variations in the response format. When the callback and context arguments are not supplied, the response format is a simple JSON object similar to the three snippets shown below:

JSON Response for Load Feed

{
  "responseData" : {
    "feed" : {}
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
}

JSON Response for Find Feed

{
  "responseData" : {
    "query" : query-string,
    "entries" : []
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
}

JSON Response for Lookup Feed

{
  "responseData" : {
    "query" : query-value -e.g.- original-url,
    "url" : primary-url-for-that-page
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
}

In the JSON fragments above, note that the responseData property contains a feed object, or a query property and entries array, or a query property and url property. The content returned in this property is a function of the Feed API method being accessed. For additional information please review the Result Format discussion. Note that in this portion of the document, there is an optional error object described. When using the URL based protocol, the error property is never present. Instead, the responseStatus and responseDetails properties are used. The responseStatus property contains a value of 200 on success and a non-200 http error status code on failure. If there is a failure, responseDetails contains a diagnostic string.

If the application supplies a callback argument and does not specify a context argument, it can receive the same object, only in this case it's passed as the first argument to the application specified callback.

callbackFunction({
  "responseData" : {
    "query" : query-value -e.g.- original-url,
    "url" : primary-url-for-that-page
  },
  "responseDetails" : null | string-on-error,
  "responseStatus" : 200 | error-code
})

If the application supplies both callback and context arguments, the response is encoded as a JavaScript procedure call. In this mode of operation, the value of callback becomes the procedure call target, the value of context is passed as the first argument, the value of responseData from above is passed as the second argument, the response status is passed as the third argument, and the final argument is either null or a diagnostic string.

foo('bar', {
 "feed": {
  "title": "Digg",
  "link": "http://digg.com/",
  "author": "",
  "description": "Digg",
  "type": "rss20",
  "entries": [
   {
    "title": "The Pirate Bay Moves Servers to Egypt Due to Copyright Laws",
    "link": "http://digg.com/tech_news/The_Pirate_Bay_Moves_Servers_to_Egypt_Due_to_Copyright_Laws",
    "author": "",
    "publishedDate": "Mon, 31 Mar 2008 23:13:33 -0700",
    "contentSnippet": "Due to the new copyright legislation that are going ...",
    "content": "Due to the new copyright legislation that are going to take...",
    "categories": [
    ]
   },
   {
    "title": "Millions Dead/Dying in Recent Mass-Rick-Rolling by YouTube.",
    "link": "http://digg.com/comedy/Millions_Dead_Dying_in_Recent_Mass_Rick_Rolling_by_YouTube",
    "author": "",
    "publishedDate": "Mon, 31 Mar 2008 22:53:30 -0700",
    "contentSnippet": "Click on any \u0022Featured Videos\u0022. When will the insanity stop?",
    "content": "Click on any \u0022Featured Videos\u0022. When will the insanity stop?",
    "categories": [
    ]
   },
   ...
  ]
 }
}
, 200, null)

Load Feed Specific Arguments

The Load Feed method supports a number of optional arguments which are all listed below:

Argument Description
num? This optional argument supplies the number of entries to load from the feed specified by q. A value of -1 indicates the maximum number of entries supported which at the time of this writing is 100. If this argument is not supplied, a value of 4 is assumed.
output? This optional argument determines the output format for the responseData property.
  • json - This is the default value and specifies that JSON only output is returned.
  • json_xml - When this argument is specified, the JSON representation of the feed is returned, and a new xmlString property is returned that contains the XML representation of the feed in string form.
  • xml - When this argument is specified, the JSON representation of the feed is NOT returned. Only the xmlString property is returned. This contains the XML representation of the feed in string form.
scoring? By default, when a feed is loaded, the system returns a cached copy of the specified feed that is 100% in sync with the feed contents at the time that it was cached. By setting scoring to a value of h, you can instruct the system to return any additional historical entries that it might have in its cache.

Find Feed Specific Arguments

The Find Feed method has no additional arguments. All arguments are listed above.

Lookup Feed Specific Arguments

The Lookup Feed method has no additional arguments. All arguments are listed above.