Example: Working With Google Contacts API In Ruby

As I mentioned, I’ve been working with the Google Contacts API for the past few days. The most difficult part of this process was working with the Google OAuth, but once you get past that part, the rest is pretty simple, especially with Ruby gem Nokogiri. Here is one way to interact with the Google Contacts API once you get past the OAuth process:


You can also view this code on github.

Parsing Google Contacts

#google_contacts.rb

require 'nokogiri'
require 'open-uri'
require_relative '../contact'

class Contacts
  #specify the number of contacts you need
  MAX_RESULTS = 3000 
  CLIENT_ID = "YOUR CLIENT ID"
  
  #get and parse the contacts with your access token
  def Contacts.get token
    url = "https://www.google.com/m8/feeds/contacts/default/full?client_id=#{CLIENT_ID}&access_token=#{token}&max-results=#{MAX_RESULTS}"
    p url
    
    contacts = [] #keeps track of all the contacts
    
    doc = Nokogiri::HTML(open(url))
    doc.css('entry').each do |item|
      
      #get external id
      base_uri = item.xpath('./id')[0].children.inner_text
      external_id = base_uri.gsub(/^.*/(w+)$/,'1')

      #get contact name
      first_name = ''
      middle_name = ''
      last_name = ''
      name = item.xpath('./title')[0].children.inner_text
      formatted_name_array = name.split
      if formatted_name_array.size == 2
        first_name = formatted_name_array[0]
        last_name = formatted_name_array[1]
      elsif formatted_name_array.size == 3
        first_name = formatted_name_array[0]
        middle_name = formatted_name_array[1]
        last_name = formatted_name_array[2]
      elsif formatted_name_array.size == 1
        first_name = formatted_name_array[0]
      else
        first_name = formatted_name_array[0]
        middle_name = formatted_name_array[1]
        last_name = formatted_name_array[-1]
      end
        
      #get contact email addresses
      email_addresses = []
      i = 0
      item.xpath('./email').each do |email|
        email_addresses << item.xpath('./email')[i].attributes['address'].inner_text
        i+=1
      end
      p email_addresses

      #get phone numbers
      j = 0
      phone_numbers = []
      if item.xpath('./phonenumber')[0] != nil
        item.xpath('./phonenumber').each do |number|
          phone_numbers << item.xpath('./phonenumber')[j].children.inner_text
          i +=1
        end
      end
      p phone_numbers
      
      #create a new contact - see below code for the Contact object
      contact = Contact.new({
        :source => 'google',
        :external_id => external_id,
        :first_name => first_name,
        :middle_name => middle_name,
        :last_name => last_name,
        :emails => email_addresses,
        :phones => phone_numbers
      })
      contacts.push( contact  )
    end
    contacts
  end
  
end

The Contact Object

require 'json'

class Contact 
  attr_reader :source , :external_id , :first_name , :middle_name, :last_name , :phones , :emails 

  def initialize args = {}
    args.each do |k,v|
      next if ( k == 'phones' || k == 'emails' ) && v.class != 'Array'
    	instance_variable_set("@#{k}",v) unless v.nil?
    end
  end
  
  #create a json represenation of the contact
  def to_json(options = {},option2 = 0)
    JSON.generate(self.to_hash)
  end
  
  #create a hash represenation of the contact
  def to_hash fields = []
  	hash = {}
  	strip_fields = []
  	self.instance_variables.each{|var| 
  		if fields.length > 0
  			next unless fields.include? var.to_s.delete("@")
  		end
  		hash[var.to_s.delete("@")] = self.instance_variable_get(var) unless strip_fields.include? var.to_s
  	}
  	hash
  end
  
  #create a string representation of the contact
  def to_s
    "First Name: #{first_name}, Middle Name: #{middle_name}, Last Name: #{last_name}, Phones: #{phones}, Emails: #{emails}, Source: #{source} , Id: #{external_id}"
  end
end 

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.

  • thanks!

  • Hey,
    I am also working on Google shared contact API. And using https://github.com/jparker/gauthic this plugin for it. It seems create/retrieve records, but I am not able to see the contacts in my account. Any Idea ?

    Thanks,
    Pravin.

  • Phil Pirozhkov

    made my day, thanks!

  • Daniel Fahy

    The link to the Github is showing the 404 page. Did you forget to allow permissions ?