Click here to see your recently viewed pages and most viewed pages.
Hide

Google Contacts API v1 Developer's Guide: .NET

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 a user's contacts. Contacts are stored in the user's Google Account; most Google services have access to the contact list.

Your client 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 how to interact with contacts using the .NET 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 .NET client applications that can interact with Google's contact lists.

This document assumes that you understand the general ideas behind the Google Data APIs protocol.

For reference information about the classes and methods provided by the client library, see the .NET client library API reference. For general Contacts Data API reference information, see the Protocol reference guide.

Getting started

For help setting up the client library, see the Getting Started Guide.

The .NET client library requires the .NET 2.0 runtime. After downloading the client library, you'll find the DLLs you need to get started in the Redist subdirectory of the distribution.

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.

Running the example code

To compile the examples in this document into your own code, you'll need the following using statements:

using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;

Authenticating

All Contacts Data API feeds are private. Thus, your client needs to authenticate before accessing a contacts feed. It can authenticate using either of two approaches: ClientLogin username/password authentication or AuthSub proxy authentication.

For more information about authentication with Google Data APIs in general, see the authentication documentation.

AuthSub proxy authentication

The AuthSub login protocol allows your web-based application to have a user authenticate through Google's servers. To familiarize yourself with how this works in .NET, please read this article on the basics of using AuthSub in the .NET client library.

Having reviewed that documentation, you can now make a few substitutions and use it to access the Contacts Data API:

authSubUrl = AuthSubUtil.getRequestUrl("http://www.example.com/Hello.asp", 
"http://www.google.com/m8/feeds/", false, true);

Here we request a token with the proper scope to access contacts.

GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", 
"exampleCo-exampleApp-1");
authFactory.Token = (String) Session[[]"token"];
ContactsService service = new ContactsService(authFactory.ApplicationName);
service.RequestFactory = authFactory;

Note that the service name for the Contacts Data API is "cp".

ClientLogin username/password authentication

Use ClientLogin authentication if your client is a standalone, single-user "installed" client (such as a desktop application). Just call the setUserCredentials method on your ContactsService object and all subsequent interactions with contacts will be authenticated:

ContactsService service = new ContactsService("exampleCo-exampleApp-1");
service.setUserCredentials("liz@gmail.com", "password");

For more information about ClientLogin authentication, including sample requests and responses, see the Account Authentication for Installed Applications documentation.

Creating contacts

You can use the .NET client library to publish new contact entries.

First, create a ContactEntry object to represent the contact. Then you can set the name, notes and other attributes of the contact. Finally, use the ContactsService object to insert the contact. Here's an example of how to publish a new contact:

ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = "John Doe";

EMail primaryEmail = new EMail("johndoe@example.com");
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);

EMail secondaryEmail = new EMail("johndoe@a.com");
secondaryEmail.Rel = ContactsRelationships.IsHome;
newEntry.Emails.Add(secondaryEmail);

PhoneNumber phoneNumber = new PhoneNumber("555-555-5555");
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);

PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = "123 somewhere lane";
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsHome;
newEntry.PostalAddresses.Add(postalAddress);

newEntry.Content.Content = "Who is this guy?";

Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

ContactEntry createdEntry = (ContactEntry) service.Insert(feedUri, newEntry);

The Insert method takes the service's post URL as a parameter. Then the method returns the entry as it was stored by the server. The entry returned is the same one you sent, but it also contains various elements added by the server, such as a contact ID.

If your request fails for some reason, Google may return a different status code. For information about the status codes, see the Google Data API protocol reference document.

Retrieving contacts

Retrieving all contacts

To retrieve the user's contacts, create a ContactsQuery object with the contact feed URL:

ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));

ContactsFeed feed = service.Query(query);

foreach (ContactEntry entry in feed.Entries)
{
  Console.WriteLine(entry.Title.Text);
  foreach (EMail email in entry.Emails)
  {
    Console.WriteLine("\t" + email.Address);
  }
}

Note: The feed may not contain all of the user's contacts, because there's a default limit on the number of results returned. To retrieve all of the contacts you can page through the feed using the 'max-results' and 'start-index' parameters. These are discussed in the Retrieving contacts using query parameters section.

Retrieving contacts using query parameters

The Contacts Data API lets you request a set of contacts that match specified criteria, such as requesting contacts created or updated in a given date range, or published by a particular author. To do this, you create a ContactsQuery object and pass it to the ContactsService.Query() method.

For example, to send a date-range query, use the StartDate property of the ContactsQuery object. The following code snippet prints out each contact updated after the given start time of January 1, 2008:

ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
query.StartDate = new DateTime(2008, 1, 1);

ContactsFeed feed = service.Query(query);

foreach (ContactEntry entry in feed.Entries)
{
  Console.WriteLine(entry.Title.Text);
  Console.WriteLine("Updated on: " + entry.Updated.ToString());
}

Notice that the ContactsQuery object is constructed using the same contact feed URL used to retrieve contacts.

The Contacts Data API supports the following ContactsQuery properties:

NumberToRetrieve
Set the maximum number of entries to return.
StartIndex
Sets the 1-based index of the first result to be retrieved (for paging through results).
StartDate
Set the lower bound on entry update dates.
ShowDeleted
Include deleted contacts in the returned contacts feed. Deleted contacts are shown as entries that contain nothing but an <atom:id> element and a <gd:deleted> element. (Google retains placeholders for deleted contacts for 30 days after deletion; during that time, you can request the placeholders using the showdeleted query parameter.)
OrderBy
You can use the value "lastmodified" to have the contacts returned by last-modified date.
SortOrder
Set sorting order direction. This can be either "ascending" or "descending".

Note: To track incremental changes to a contact list, do the following: When you send a request for a feed, keep track of the value of the feed's <updated> element. Then you can later retrieve only the contacts that have changed since the previous request by setting updated-min to that <updated> value, and setting showdeleted to true.

For more information about query parameters, see the Contacts Data API Reference Guide and the Google Data APIs Reference Guide. In particular, there is no support for full-text queries or locating a contact by email address.

Note: By default, the entries in a feed are not ordered.

Updating contacts

To update an existing contact, first retrieve the entry you want to update, modify it, and then send it to the server using the Update method. The following code snippet modifies a previously retrieved ContactEntry.

Organization org = new Organization();
org.Rel = ContactsRelationships.IsWork;
org.Title = "President, CEO";
org.Name = "John Doe Enterprises";
org.Primary = true;
entry.Organizations.Add(org);
ContactEntry updatedEntry = (ContactEntry) entry.Update();

The above code returns a ContactEntry containing the entire newly-updated post. To update any other properties, simply set them in the ContactEntry object before calling Update.

Deleting contacts

To delete a contact, call the Delete method on your ContactEntry object:

entry.Delete();

Note: To update existing contacts, see Updating contacts; don't update by deleting contacts and then re-adding them.