AndreasU
AndreasU

Reputation: 38

Using Google API to modify google contacts

I want to start developing with Google API’s with a .NET client. For first step I tried to get all google contacts and now I want to insert contacts. I have read a lot about Google API’s to CRUD (create, read, update and delete) contacts. There are the Contact API, the People API and other(?). What is the best way to CRUD contacts?

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
  new ClientSecrets
  {
    ClientId = "xyz.apps.googleusercontent.com",
    ClientSecret = " xyz"
  },
  new[] { "profile", "https://www.google.com/m8/feeds/contacts/xy%40gmail.com/full" },
  "me",
  CancellationToken.None).Result;

// Create the service.
var peopleService = new PeopleService(new BaseClientService.Initializer()
{
  HttpClientInitializer = credential,
  ApplicationName = "WindowsClient-Google-Sync",
});

ListRequest listRequest = peopleService.People.Connections.List("people/me");
listRequest.SyncToken = null;
ListConnectionsResponse result = listRequest.Execute();

foreach (Person person in result.Connections)
{
  foreach (Name name in person.Names)
  {
    Console.WriteLine("Name: " + name.DisplayName);
  }
}

How can I extend this sample to create or update contacts?

Thanks

Andreas

Upvotes: 2

Views: 2397

Answers (1)

Mr.Rebot
Mr.Rebot

Reputation: 6791

If you will check Google Contacts API:

The Google Contacts 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 Google Contacts API to create new contacts, edit or delete existing contacts, and query for contacts that match particular criteria

Creating Contact

To create a new contact, send an authorized POST request to the user's contacts feed URL with contact data in the body.

The URL is of the form:

https://www.google.com/m8/feeds/contacts/{userEmail}/full

Upon success, the server responds with an HTTP 201 Created status code and the created contact entry with some additional elements and properties (shown in bold) that are set by the server, such as id, various link elements and properties.

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;
import com.google.gdata.data.extensions.City;
import com.google.gdata.data.extensions.Country;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.FormattedAddress;
import com.google.gdata.data.extensions.FullName;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.data.extensions.PhoneNumber;
import com.google.gdata.data.extensions.PostCode;
import com.google.gdata.data.extensions.Region;
import com.google.gdata.data.extensions.Street;
import com.google.gdata.data.extensions.StructuredPostalAddress;
// ...
public static ContactEntry createContact(ContactsService myService) {
  // Create the entry to insert.
  ContactEntry contact = new ContactEntry();
  // Set the contact's name.
  Name name = new Name();
  final String NO_YOMI = null;
  name.setFullName(new FullName("Elizabeth Bennet", NO_YOMI));
  name.setGivenName(new GivenName("Elizabeth", NO_YOMI));
  name.setFamilyName(new FamilyName("Bennet", NO_YOMI))
  contact.setName(name);
  contact.setContent(new PlainTextConstruct("Notes"));
  // Set contact's e-mail addresses.
  Email primaryMail = new Email();
  primaryMail.setAddress("[email protected]");
  primaryMail.setDisplayName("E. Bennet");
  primaryMail.setRel("http://schemas.google.com/g/2005#home");
  primaryMail.setPrimary(true);
  contact.addEmailAddress(primaryMail);
  Email secondaryMail = new Email();
  secondaryMail.setAddress("[email protected]");
  secondaryMail.setRel("http://schemas.google.com/g/2005#work");
  secondaryMail.setPrimary(false);
  contact.addEmailAddress(secondaryMail);
  // Set contact's phone numbers.
  PhoneNumber primaryPhoneNumber = new PhoneNumber();
  primaryPhoneNumber.setPhoneNumber("(206)555-1212");
  primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
  primaryPhoneNumber.setPrimary(true);
  contact.addPhoneNumber(primaryPhoneNumber);
  PhoneNumber secondaryPhoneNumber = new PhoneNumber();
  secondaryPhoneNumber.setPhoneNumber("(206)555-1213");
  secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
  contact.addPhoneNumber(secondaryPhoneNumber);
  // Set contact's IM information.
  Im imAddress = new Im();
  imAddress.setAddress("[email protected]");
  imAddress.setRel("http://schemas.google.com/g/2005#home");
  imAddress.setProtocol("http://schemas.google.com/g/2005#GOOGLE_TALK");
  imAddress.setPrimary(true);
  contact.addImAddress(imAddress);
  // Set contact's postal address.
  StructuredPostalAddress postalAddress = new StructuredPostalAddress();
  postalAddress.setStreet(new Street("1600 Amphitheatre Pkwy"));
  postalAddress.setCity(new City("Mountain View"));
  postalAddress.setRegion(new Region("CA"));
  postalAddress.setPostcode(new PostCode("94043"));
  postalAddress.setCountry(new Country("US", "United States"));
  postalAddress.setFormattedAddress(new FormattedAddress("1600 Amphitheatre Pkwy Mountain View"));
  postalAddress.setRel("http://schemas.google.com/g/2005#work");
  postalAddress.setPrimary(true);
  contactOne.addStructuredPostalAddress(postalAddress);
  // Ask the service to insert the new entry
  URL postUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
  ContactEntry createdContact = myService.insert(postUrl, contact);
  System.out.println("Contact's ID: " + createdContact.getId());
  return createdContact;
}

Update Contact

To update a contact, first retrieve the contact entry, modify the data and send an authorized PUT request to the contact's edit URL with the modified contact entry in the body.

The URL is of the form:

https://www.google.com/m8/feeds/contacts/userEmail/full/{contactId}

To ensure that the data sent to the API doesn't overwrite another client's changes, the contact entry's Etag should be provided in the request header.

If-Match: Etag

Upon success, the server responds with an HTTP 200 OK status code and the updated contact entry.

public static ContactEntry updateContactName(
    ContactsService myService, URL contactURL)
    throws ServiceException, IOException {
  // First retrieve the contact to updated.
  ContactEntry entryToUpdate = myService.getEntry(contactURL, ContactEntry.class);
  entryToUpdate.getName().getFullName().setValue("New Name");
  entryToUpdate.getName().getGivenName().setValue("New");
  entryToUpdate.getName().getFamilyName().setValue("Name");
  URL editUrl = new URL(entryToUpdate.getEditLink().getHref());
  try {
    ContactEntry contactEntry = myService.update(editUrl, entryToUpdate);
    System.out.println("Updated: " + contactEntry.getUpdated().toString());
    return contactEntry;
  } catch (PreconditionFailedException e) {
    // Etags mismatch: handle the exception.
  }
  return null;
}

Delete Contact

To delete a contact, send an authorized DELETE request to the contact's edit URL.

The URL is of the form:

https://www.google.com/m8/feeds/contacts/{userEmail}/full/{contactId}

To ensure that the data sent to the API doesn't overwrite another client's changes, the contact entry's Etag should be provided in the request header.

If-Match: Etag

Upon success, the server responds with an HTTP 200 OK status code.

public static void deleteContact(ContactsService myService, URL contactURL)
    throws ServiceException, IOException {
  // Retrieving the contact is required in order to get the Etag.
  ContactEntry contact = myService.getEntry(contactURL, ContactEntry.class);

  try {
    contact.delete();
  } catch (PreconditionFailedException e) {
    // Etags mismatch: handle the exception.
  }
}

while People API:

The People API lets you list authenticated users' Contacts and retrieve profile information for authenticated users and their contacts.

For example, let's say the authenticated user, Jen, has Fabian and Ranjith in her private contacts. When your app calls people.connections.list to retrieve a list of her connections, Jen is presented with a consent screen asking to give the app access to the list. If Jen consents, the app retrieves a list containing Fabian and Ranjith (with a resource name for each person). The app can then call people.get, passing in a resource name, to get private contact and public profile data for each person.

Upvotes: 1

Related Questions