How to get my gmail contacts with Javascript & Google API

Published —

In web applications it’s a useful functionality if you let users to import their google contacts to the site.
You can import your Gmail contacts easily with the Google API and a “couple” of JavaScript functions. Here is how…

1. – First of all we are going to Google Developers Console logged with our gmail account and we will create a new project.

1

2. – After that, we have to add the ‘Google People API’ to our project. Search & find it. We choose People API because doesn’t allow to add, edit or delete contacts… but we don’t need that, aren’t we?

google api

3. – Now we need to configure the OAuth 2 API credentials. Google console show us a warning about that. So Let’s ‘Go to credentials’
We’ll only need a Client ID OAuth credential here. Fill the name field and add our allowed domain and callback page urls (you can add http://localhost/myproject to test it)
Ex: www.mydomain.com & www.mydomain.com/samplecallback.

4

Last step configures the appearance of ‘Google Consent Screen’ with your web page name and a small logo (optional).

4. – Now it’s time to code! Open a new blank HTML page and add this script:

<script src="https://apis.google.com/js/client.js"></script>

We’ll add this HTML code to test the API, we only need a div to print the contacts table dynamically and a button to fire the API call (authClick function):

<body>
<h3>Get your contacts using People API</h3>     
<p>Press button to Authorize and Download your Contacts in JSON  <br /><br />
<button onclick="authClick(event)">Load Contacts</button>     
</p>     
<div id="divauthresult"></div>     
<div id="divtableresult"></div>   
</body>

4 functions it’s all we need to authorize with google and download a json with user contacts.

function authClick() {
// Your Client ID is retrieved from your project
//in the Developer Console =&gt; https://console.developers.google.com
    var CLIENT_ID = 'mygoogleid.apps.googleusercontent.com';
    var SCOPES = ["https://www.googleapis.com/auth/contacts.readonly"];
 
    gapi.auth.authorize(
        { client_id: CLIENT_ID, scope: SCOPES, immediate: false }, authResult);
 
     return false;
}
 
/**
* Handle response from authorization server.
* @param {Object} authResult Authorization result.
*/
function authResult(_Result)
{
    var _Div = document.getElementById('divauthresult');
    if (_Result &amp;&amp; !_Result.error)
    {
        // Auth OK! =&gt; load API.
        _Div.style.display = 'none';
        loadPeopleApi();
    }else{
        // Auth Error, allowing the user to initiate authorization by
        _Div.innerText = ':( Authtentication Error : ' + _Result.error;
    }
}
 
/**
* Load Google People client library. List Contact requested info
*/
function loadPeopleApi()
{
    gapi.client.load('https://people.googleapis.com/$discovery/rest',
        'v1',
        showContacts);
}

authClick function needs a SCOPE and the ClientID we got from google developers console. It will try to authorize the user.
If authorization is ok loadPeopleApi will execute the request in the next showContacts function :

/**
* Show Contacts Details display on a table pagesize = 100 connections.
*/
function showContacts()
{
    var request = gapi.client.people.people.connections.list({
        'resourceName': 'people/me',
            'pageSize': 100,
            'requestMask.includeField': '
                person.phone_numbers,person.organizations,person.email_addresses,person.names'
        });
 
    request.execute(function(resp) {
        var connections = resp.connections;
 
        if (connections.length &gt; 0)
        {
            var _Html = "&lt;table&gt;&lt;tr&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Email&lt;/th&gt;&lt;th&gt;Company&lt;/th&gt;&lt;th&gt;Phone&lt;/th&gt;&lt;/tr&gt;";
            var _EmptyCell = "&lt;td&gt; - &lt;/td&gt;";
 
            for (i = 0; i &lt; connections.length; i++)
            {
                var person = connections[i];
                _Html += "&lt;tr&gt;";
 
                if (person.names &amp;&amp; person.names.length &gt; 0)
                    _Html += "&lt;td&gt;" + person.names[0].displayName + "&lt;/td&gt;";
                else
                    _Html += _EmptyCell;
 
                if (person.emailAddresses &amp;&amp; person.emailAddresses.length &gt; 0)
                _Html += "&lt;td&gt;" + person.emailAddresses[0].value + "&lt;/td&gt;";
                else
                    _Html += _EmptyCell;
 
            if (person.organizations &amp;&amp; person.organizations.length &gt; 0)
            _Html += "&lt;td&gt;" + person.organizations[0].name + "&lt;/td&gt;";
            else
            _Html += _EmptyCell;
 
            if (person.phoneNumbers &amp;&amp; person.phoneNumbers.length &gt; 0)
            _Html += "&lt;td&gt;" + person.phoneNumbers[0].value + "&lt;/td&gt;";
        else
            _Html += _EmptyCell;
 
            _Html += "&lt;/tr&gt;";
            }
            divtableresult.innerHTML = "Contacts found : &lt;br&gt;" + _Html;
        } else {
            divtableresult.innerHTML = "";
            divauthresult.innerText = "No Contacts found!";
        }
    });
}

Note we have added people.connections.list with 3 params:

  • ResourceName : Required. Here only allows ‘people/me’
  • PageSize : Contacts pagination. Max allowed = 500
  • requestMask.includeField : It’s really important to add this param if you want to get more contact field info like contact email, phone or company. By default API only returns contact displayname in the json. We have included in the demo ‘person.phone_numbers, person.organizations, person.email_addresses, person.names’. You can see more contacts fields here!

5. – You can download full html sample in my github

DC

Comments (4)

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Articles That Might
Interest You

ASP Net Core Service Lifetime

If you are going to use dependency injection framework in Net Core you must control the service …

Configure SSL to securely connect to Azure Database for MySQL

Azure DB for MySQL supports connecting to client applications using SSL. Enforcing SSL between y…

Generate dynamically a signed Pdf with Net Core 5 (C#)

Do you need to generate a certificate, diploma, or any pdf document signed with your own pfx? He…

Subscribe to Our Newsletter


© acbteam | All rights reserved.