Contacts API v2

Google Contacts API v2 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 feed and the contact groups feed provided in the Contacts Data API to create new contacts and contact groups, edit or delete existing contacts and contact groups, and query for contacts and contact groups 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 sample code

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

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

Note: If using the AuthSub proxy authentication, add the System.Net namespace directive as well.

Authenticating

All Contacts Data API feeds are private read/write feeds. 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 proxy authentication is used by web applications that need to authenticate their users to Google Accounts. The web site operator and the client code don't have access to the username and password for the user; instead, the client obtains special AuthSub tokens that allow the client to act on a particular user's behalf. To familiarize yourself with how this works in .NET, please read this article on the basics of using AuthSub in the .NET client library. For more detailed information about AuthSub authentication in general, see the AuthSub documentation.

When a user first visits your application, they have not yet been authenticated. In this case, you need to display some information and a link directing the user to a Google page to authenticate your request for access to their contacts.

Having reviewed the documentation for using AuthSub in a .NET client library, you can now make a few substitutions and use it to access the Contacts Data API:

authSubUrl = AuthSubUtil.getRequestUrl("http://www.example.com/Welcome.asp",
"https://www.google.com/m8/feeds/", false, true);
  • The http://www.example.com/Welcome.asp string is your target where the user is redirected to after a successful authentication.
  • The https://www.google.com/m8/feeds/ string is the scope, one of the Contacts Data API feeds (contacts and contacts groups). For more information about the Contacts Data API feeds, see the Contacts feed URL or the Contacts groups feed URL.
  • The secure boolean value used when a client requests a secure token and is false by default
  • The session boolean value which, when true, means you want a session token and not just a one-time use token.

After generating the AuthSub token, create a RequestSettings object to hold the company name and token. With this settings object, create a contact request for the AuthSub authentication:

GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp",
"exampleCo-exampleApp-1");
RequestSettings rs = new RequestSettings("exampleCo-exampleApp-1", (String) Session["token"]);
ContactsRequest cr = new ContactsRequest(rs);

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). First create a request setting with the company name source, the email address, and the password. Then create a contacts request object with the request settings:

RequestSettings rs = new RequestSettings("exampleCo-exampleApp-1", "liz@gmail.com", "password");
ContactsRequest cr = new ContactsRequest(rs);

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 Contact object to represent the contact. Then you can set the name, notes and other attributes of the contact. Finally, use the ContactsRequest object to insert the contact. Here's an example of how to publish a new contact:

Contact newContact = new Contact();
newContact.Title.Text = "Liz Doe";

EMail primaryEmail = new EMail("liz@gmail.com");
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newContact.Emails.Add(primaryEmail);

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

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

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

newContact.Content = "Contact information for Liz";

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

//The example assumes the ContactRequest object (cr) is already set up.
Contact createdContact = cr.Insert(feedUri, newContact);

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

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.

Note: A photo cannot be added to a contact while creating the contact. Once the contact exists, see Adding a photo for a contact for more information.

Adding a photo for a contact

A photo can be added to a contact after the contact is created. An example of adding a photo:

public static void AddContactPhoto(Contact contact, ContactRequest cr, Stream photoStream)
{
  cr.SetPhoto(contact, photoStream);
}

Retrieving contacts

Retrieving all contacts

To retrieve all of the user's contacts, set the request setting's AutoPaging property to true and create a ContactsRequest object. If the AutoPaging property is set to false, only the first 25 contacts are returned. For more information about the AutoPaging property, see the RequestSettings Class of the Google.GData.Client namespace:

RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
 // AutoPaging results in automatic paging in order to retrieve all contacts
 rs.AutoPaging = true;
 ContactsRequest cr = new ContactsRequest(rs);

 Feed<Contact> f = cr.GetContacts();
 foreach (Contact e in f.Entries)
 {
   Console.WriteLine("\t" + e.Title);
   foreach (EMail email in e.Emails)
   {
      Console.WriteLine("\t" + email.Address);
   }
   foreach (GroupMembership g in e.GroupMembership)
   {
      Console.WriteLine("\t" + g.HRef);
   }
   foreach (IMAddress im in e.IMs)
   {
      Console.WriteLine("\t" + im.Address);
   }
 }

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 ContactsRequest() 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);

//The example assumes the ContactRequest object (cr) is already set up.
Feed<Contact> feed = cr.Get<Contact>(query);
foreach (Contact contact in feed.Entries)
{
  Console.WriteLine(contact.Title);
  Console.WriteLine("Updated on: " + contact.Updated.ToString());
}

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

In the example code, notice that the ContactsQuery object is constructed using the same contact feed URL used to retrieve contacts.

Some of the ContactsQuery properties supported by the Contacts Data API:

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 minimum date range value 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.) The valid values for this property are true or false.
OrderBy
Use as a sorting criterion. 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".
Group
Set the group ID. The results are only contacts belonging to the specified group.

The Contacts Data API supports query parameters described in the Contacts Data API Reference Guide, the Google Data APIs Reference Guide, and in the Google.GData.Contacts namespace of the .NET client library API reference. In particular, there is no support for full-text queries or locating a contact by email address.

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.

Retrieving a single contact

To retrieve a specific contact, send a request to the contact's self link. The server returns a contact entry. For example, to get a contact with the self link set to https://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/12345, send the following HTTP request:

//The example assumes the ContactRequest object (cr) is already set up.

Contact c = cr.Retrieve<Contact>("https://www.google.com/m8/feeds/contacts/liz%40gmail.com/full/12345");

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Retrieving a single contact requires prior knowledge of the entry's self link, which can only be obtained by locating the corresponding entry in the contacts feed. For more information, see Retrieving all contacts and Retrieving contacts using query parameters.

Retrieving a contact again

If you want to retrieve a contact that you've retrieved before, you can improve efficiency by telling the server to send the contact only if it has changed since the last time you retrieved it.

To do this sort of conditional retrieval, create a ContactRequest object. If the ETags match, the contact hasn't changed, and the server returns an HTTP 304 Not Modified status code. If the ETags do not match, the contact has been modified since the last time you requested it, and the server returns the contact.

For more information about ETags, see the Google Data APIs reference guide.

/*This example sets up the etag header based on the old contact.
The example assumes the ContactRequest object (cr) is already set up.*/

Contact c = cr.Retrieve(oldContact);

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Retrieving a photo for a contact

This example shows how to retrieve a photo for a contact. When using photo links, an authorization token in the HTTP header has to be specified.

//The example assumes the ContactRequest object (cr) is already set up.

Stream photoStream = cr.GetPhoto(contact);

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

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 Contact.

/*The example assumes the Contact object (contact) and
the ContactRequest object (cr) are already set up.*/

Organization org = new Organization();
org.Rel = ContactsRelationships.IsWork;
org.Title = "President, CEO";
org.Name = "John Doe Enterprises";
org.Primary = true;
contact.Organizations.Add(org);
Contact updatedContact = cr.Update(contact);

Note: For more information about setting up Contacts and ContactRequest objects, see the Contacts instantiation in Creating contacts, and the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

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

Note: If you try to update a contact using an outdated ETag (that is, if the contact has been updated by another client since you retrieved it), you will receive an HTTP 412 Preconditioned Failed status code.

Photo management

Updating a photo is similar to adding a photo, but requires to provide the ETag of the current photo.

When using photo links, an authorization token in the HTTP header has to be specified.

To replace a photo of a contact:

/*The example assumes the Contact object (contact) and
the ContactRequest object (cr) are already set up.*/

cr.SetPhoto(contact, photoStream);

To delete a photo of a contact:

/*The example assumes the Contact object (contact) and
the ContactRequest object (cr) are already set up.*/

cr.Service.Delete(contact.PhotoUri, contact.PhotoETag);

These examples assume that the photo currently exists, and do not verify the existence of the ETags. A realistic application would probably need to do that.

Note: For more information about setting up Contacts and ContactRequest objects, see the Contacts instantiation in Creating contacts, and the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Deleting contacts

Google retains placeholders for deleted contact groups for 30 days after deletion. During this 30 day time period, you can request these placeholders using the ShowDeleted query parameter.

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

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

/*The example assumes the Contact object (contact) and
the ContactRequest object (cr) are already set up.*/

cr.Delete(contact);

Note: For more information about setting up Contacts and ContactRequest objects, see the Contacts instantiation in Creating contacts, and the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Back to top

Creating contact groups

You can create a new contact group entry after authenticating.

An example of a group entry:

Group newGroup = new Group();
newGroup.Title = "MyOwnGroup";
//The example assumes the ContactRequest object (cr) is already set up.
Group insertedGroup = cr.Insert(new Uri("https://www.google.com/m8/feeds/groups/liz%40gmail.com/full", newGroup);

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

In this example, first create a Group object and set a Title for the group's name along with other group attributes. Use the ContactsRequest object to insert the contact group.

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.

System groups

Besides the user-created contact groups, the Contacts Data API provides several predefined system groups. These groups have the same characteristics of regular contact groups except for:

  • System groups are always there for every account. They can not be deleted, and it is not possible to create new ones. It is also impossible to update them, for example by changing their name.
  • Contact group entries of system groups do not have a rel="edit" link.
  • Their entries have a special property whose presence indicates that the group is a member of the system groups. The property contains and id attribute. This system group id can be used to identify a particular system group.

The current version of the Contacts API exposes 4 system groups:

  • The My Contacts group, intended to contain all the contacts that are important for the user. Its system group id is "Contacts". This system group is limited to 20 addresses.
  • The Friends, Family, and Coworkers groups, whose intended use is obvious.

The values of the system group ids corresponding to these groups can be found in the Reference Guide for the Contacts Data API.

Note: System groups' names are not guaranteed to be localized. In general, your client is responsible for presenting the system groups in a way appropriate for your users, such as providing localized names for the system groups, or representing them using icons.

Retrieving contact groups

Retrieving all contact groups

To retrieve all contact groups and, out of all of the returned groups, to show only the system groups which are Contacts, Friends, Family, and Coworkers:

RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.PassWord);
//AutoPaging results in automatic paging in order to retrieve all groups
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);

Feed<Group> fg = cr.GetGroups();
foreach (Group g in fg.Entries)
{
  Console.WriteLine(g.SystemGroup);
}

Retrieving all contact groups using query parameters

The Contacts Data API support for contact groups includes the same Query properties as those allowed for contacts, except for the Group property used to return all contacts in a group. For more information, see the Contacts Data API Reference Guide and the Google Data APIs Reference Guide.

It allows a user to request a set of contact groups that match specified criteria, such as requesting contact groups updated after a given date.

GroupsQuery query = new GroupsQuery(GroupsQuery.CreateGroupUri("default"));
query.StartDate = new DateTime(2008, 1, 1);
//The example assumes the ContactRequest object (cr) is already set up.
Feed<Group> feed = cr.Get(query);

foreach (Group group in feed.Entries)
{
  Console.WriteLine(group.Title);
  Console.WriteLine("Updated on: " + group.Updated.ToString());
}

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Retrieving a single group

To retrieve a specific group using its self Uri:

/*The example assumes you have retrieved the group membership information for the Uri and
the ContactRequest object (cr) is already set up.*/

Group g = cr.Retrieve(new Uri("https://www.google.com/m8/feeds/groups/liz%40gmail.com/base/68f415478ba1aa69"));

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Updating contact groups

To update an existing contact group, first retrieve the entry you want to update, modify it, and then send the entry to the server using the Update method.

System groups can not be updated.

/*The example assumes you have already retrieved the group membership information for the Uri and
the ContactRequest object (cr) is already set up.*/

Group g = cr.Retrieve<Group>(new Uri("https://www.google.com/m8/feeds/groups/liz%40gmail.com/base/68f415478ba1aa69"));
g.Title = "My new Group Name";
cr.Update(g);

Note: For more information about setting up a ContactRequest object, see the example of how the RequestSettings object builds the request and how that request is passed to a ContactRequest instance in Retrieving all contacts.

Note: If you try to update a contact group using an outdated ETag (that is, if the group has been updated by another client since you retrieved it), you will receive an HTTP 412 Precondition Failed status code.

Deleting contact groups

Deleting a single contact group

To delete a contact group:

//The example assumes the ContactRequest object (cr) and the Group object (g) are already set up.

cr.Delete(g);

System groups can not be deleted.

Note: To update existing contact groups, see Updating contact groups. Do not update by deleting contact groups and then re-adding them.

Deleting all contact groups using the batch operation

If you are performing a lot of operations, use the batch requests. You can have the server perform multiple operations with a single HTTP request. Batch requests are limited to 100 operations at a time. You can find more information about batch operations in the Google Data APIs Batch Processing documentation.

To delete all contacts use the contactsrequest.Batch operation. For this operation, create a LIST<type>, you set the BatchData for each contact item, and then pass the list to the contactsrequest.Batch operation.

private void DeleteAllContacts()
{
  RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord);
  rs.AutoPaging = true // this will result in automatic paging for listing and deleting all contacts
  ContactsRequest cr = new ContactsRequest(rs);
  Feed<Contact> f = cr.GetContacts();
  List<Contact> list = new List<Contact>();
  int i=0;
  foreach (Contact c in f.Entries)
  {
    c.BatchData = new GDataBatchEntryData();
    c..BatchData.Id = i.ToString();
    c.BatchData.Type = GDataBatchOperationType.delete;
    i++;
    list.Add(c);
  }
  cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.insert);
  f = cr.GetContacts();
  Assert.IsTrue(f.TotalResults == 0, "Feed should be empty now");
}

Back to top

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.