Google Apps Platform

Google Contacts API v1 Developer's Guide: JavaScript

Important: Versions 1 and 2 of the Google Contacts API have been officially deprecated as of April 20, 2012. They will continue to work as per our deprecation policy, but we encourage you to move to version 3.

The Contacts Data API allows client applications to view and update the contacts stored in your Google account in the form Google Data API feeds.

Your application can use the Contacts Data API to create new contacts, edit or delete existing contacts, and query for contacts that match particular criteria.

In addition to providing some background on the capabilities of the Contacts Data API, this document provides examples of basic Data API interactions using the JavaScript client library. If you're interested in understanding more about the underlying protocol that the library uses, see the Protocol section of this developer's guide.

Contents

Audience

This document is intended for programmers who want to write JavaScript client applications that can interact with your Google Contacts. It provides a series of examples of basic Contacts Data API interactions using the JavaScript client library.

For Contacts Data API reference information, see the Protocol reference guide. This document assumes that you understand the general ideas behind the Google Data APIs protocol and the data model and control flow used by the JavaScript client library. It also assumes that you know how to program in JavaScript.

For reference information about the classes and methods provided by the client library, see the JavaScript client library API reference.

This document is designed to be read in order; each example builds on earlier examples.

Terms of use

You agree to abide by the Google JavaScript client library Terms of Use when using the JavaScript client library.

About supported environments

Currently, we only support JavaScript client applications that run in a web page in a browser. Currently supported browsers are Firefox 1.5 and higher, and Internet Explorer 6.0 and higher.

The JavaScript client library handles all communication with the Contacts API server. If you're an experienced JS developer, you may be thinking, "But what about the same origin policy?" The JavaScript client library allows your client to send Google Data API requests from any domain while remaining compliant with the browser security model.

Getting started

Before you can write a JavaScript client application, you need to do some setup by acquiring the library.

Creating a Google Account

You may want to sign up for a Google Account for testing purposes. Contacts are associated with Google Accounts, so if you already have a Google Account, you're all set.

Note: To view your contacts without using the Contacts Data API, you can log in to Gmail and click the Contacts link.

Acquiring the library

Before your client can use the client library, the client has to request the client library code from the server.

Start by using a <script> tag in the <head> section of your HTML document to fetch the Google AJAX API loader:

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

To acquire the Google Data API client library after fetching the loader, use the following line in your JavaScript setup code, which must be called from the <head> section of your HTML document (or from a JavaScript file that's included using a <script> tag in the <head> section of your HTML document):

google.load("gdata", "1.x");

The second parameter to google.load() is the requested version number of the JavaScript client library.  Our version numbering scheme is modeled after the one used by the Google Maps API. Here are the possible version numbers and what they mean:

"1"
The second-to-last revision of major version 1.
"1.x"
The very latest revision of major version 1.
"1.s"
The latest stable revision of major version 1. We will occasionally declare a certain version of the client library to be "stable," based on feedback we receive from developers. However, that version may not have the latest features.
"1.0", "1.1", etc
A specific version of the library, with a specified major and minor revision number.

After you've called google.load(), you have to tell the loader to wait until the page finishes loading and then call your code:

google.setOnLoadCallback(initFunc);

Where initFunc() is a function that we'll define in a later section of this document. Use this approach instead of having an onload handler attached to the <body> element.

Back to top

Authenticating to the Contact service

You can access both public and private feeds using the Contacts Data API. Public feeds don't require any authentication, but they are read-only. If you want to modify blogs, then your client needs to authenticate before requesting private feeds.

The JavaScript client library uses the AuthSub authentication system. For more information about authentication with Google Data APIs in general, see the authentication documentation.

AuthSub proxy authentication

AuthSub proxy authentication is used by web applications that need access to a user's Google data. The website operator and the client code don't have access to the username and password for the Contacts user; instead, the client obtains special AuthSub tokens that allow the client to act on a particular user's behalf.

Here's a brief overview of what happens during the authorization process for a web-based JavaScript client:

  1. The client application calls the google.accounts.user.login() method provided by the client library, passing it a "scope" value that indicates which Google service to use. For Contacts, the scope is "https://www.google.com/m8/feeds".
  2. The client library sends the browser to Google's "Access Request" page, where the user can enter their credentials to log in to the service.
  3. If the user logs in successfully, then the AuthSub system sends the browser back to the web client's URL, passing along the authentication token.
  4. The JavaScript client library stores the token in a cookie and returns control to the function that originally called google.accounts.user.login().
  5. When the client application subsequently calls client library methods that interact with Contacts, the client library automatically attaches the token to all requests.

Note: For the JavaScript client library to make authenticated Contacts API requests in a web browser, your page must contain an image that's hosted at the same domain as your page. It can be any image, even a single-pixel transparent image, but there must be an image on the page. If you want the image to not appear on your page, you can use the style attribute of the <img> tag to position the image outside the rendering area. For example: style="position:absolute; top: -1000px;"

Here's the client-application code that handles logging and creates a connection (represented by a google.gdata.contacts.ContactService object) to your Google Contacts.

var contactsService;

function setupContactsService() {
  contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}

function logMeIn() {
  var scope = 'https://www.google.com/m8/feeds';
  var token = google.accounts.user.login(scope);
}

function initFunc() {
  setupContactsService();
  logMeIn();
  getMyContacts();
}

Note that we're making contactsService a global variable, for ease of use in later functions. We'll define the function getMyContacts() below.

Tip: We strongly recommend that you provide a login button or other user input mechanism to prompt the user to start the login process manually. If you call google.accounts.user.login() immediately after the page is loaded, then the first thing the user sees on arrival to your site is a Google login page. If the user decides not to log in, then Google does not direct them back to your page; so from the user's point of view, they tried to visit your page but were sent away and never sent back. This scenario may be confusing and frustrating to users. In the example code in this document, we'll be calling google.accounts.user.login() immediately after loading in order to keep the example simple, but we don't recommend this approach for real-world client applications.

Note that you don't have to do anything with the variable named token; the client library keeps track of the token, so you don't have to.

Note: When you create a new google.gdata.contacts.ContactService object, the client library calls a method named google.gdata.client.init(), which checks that the browser the client is running in is supported. If there's an error, then the client library displays an error message to the user. If you want to handle this sort of error yourself, then you can explicitly call google.gdata.client.init(handleInitError) before you create the service, where handleInitError() is your function. If an init error occurs, then your function receives a standard Error object; you can do whatever you want with that object.

The token remains valid until you revoke it by calling google.accounts.user.logout():

function logMeOut() {
  google.accounts.user.logout();
}

If you don't call google.accounts.user.logout(), then the cookie that stores the token lasts for two years, unless the user deletes it. The cookie is retained across browser sessions, so the user can close their browser and then reopen it and come back to your client and they'll still be logged in.

However, there are certain unusual circumstances in which a token can become invalid during a session. If the Contacts API rejects a token, your client should handle the error condition by calling google.accounts.user.logout() to remove the cookie containing the current token, and then call google.accounts.user.login() again to acquire a new, valid token.

There are two other AuthSub methods that you may find useful in various contexts:

  • google.accounts.user.checkLogin(scope) tells you whether or not the browser currently has an authentication token for the given scope.
  • google.accounts.user.getInfo() provides detailed information about the current token, for debugging use.

For details about using JavaScript to interact with AuthSub, including information on token management and on checkLogin() and getInfo(), see the Using "AuthSub" Authentication with the JavaScript client library document.

Retrieving a list of contacts

The Contacts Data API provides a feed that returns a list of contacts for a particular user; that feed is known as the contacts feed.

The following sample code defines the getMyContacts() function and the callback needed to process the resulting feed:

function getMyContacts() {
  var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
  var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
  
  // Set the maximum of the result set to be 5
  query.setMaxResults(5);
  
  contactsService.getContactFeed(query, handleContactsFeed, handleError);
}

var handleContactsFeed = function(result) {
  var entries = result.feed.entry;

  for (var i = 0; i < entries.length; i++) {
    var contactEntry = entries[[]i];
    var emailAddresses = contactEntry.getEmailAddresses();
    
    for (var j = 0; j < emailAddresses.length; j++) {
      var emailAddress = emailAddresses[[]j].getAddress();
      alert('email = ' + emailAddress);
    }    
  }
}

Note that contactsService is our global variable from earlier.

The specified contactsFeedUri variable is the default contacts feed URL; it allows you to work with the authenticated user's contacts. Alternatively, you may replace default in this variable with the authenticated user's email address:

https://www.google.com/m8/feeds/contacts/joe.smith@gmail.com/full

Note: Retrieving another user's contacts is not supported by the current version of the Contacts API.

After setting up the service, getMyContacts() calls the client library's getContactFeed() method which returns the user's contacts feed as a json object.

In the call to getContactFeed(), the second argument is handleContactsFeed, which is a callback function. The API processes the request and then, if the request was successful, passes a "feed root" object containing the requested feed to the callback. A feed root is a container object that contains a feed.

The third argument to getContactFeed() is an optional error-handling function; if the client library encounters an error, it calls the specified error handler instead of the success callback function. The object that the client library passes as the argument to the error handler is an instance of the JavaScript Error object, with an additional cause property.

Here's a simple version of the error handler:

function handleError(e) {
  alert("There was an error!");
  alert(e.cause ? e.cause.statusText : e.message);
}

We're handling errors by simply displaying them to the user; your client's error handler should probably be more sophisticated. In some contexts, there may be no cause specified, so in those cases our example error handler falls back to displaying the standard message property.

Back to top

Interactive tutorial samples

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.