Google APIs is a set of application programming interfaces (APIs) developed by Google which allow communication with Google Services and their integration to other services. Third-party apps can use these APIs to take advantage of or extend the functionality of the existing services.

Setting up API Key

An API Key is a code passed in by computer programs calling an application programming interface to identify the calling program, its developer, or its user to the Website.

Steps to create API Key

1. From the Google Console, select / create project under project menu.

2. From API Manager Dashboard, click Enable API option if not done previously.

3. Select Credentials under API Manager and click Create Credentials.

4. From the options, select API Key option.

5. Now you will get an popup with new generated API Key.

 

Setting up OAuth 2.0

To use OAuth 2.0 in your application, you need an OAuth 2.0 client ID, which your application uses when requesting an OAuth 2.0 access token.

Steps to create OAuth 2.0 client ID

1. From the Google Console, select / create project under project menu.

2. From API Manager Dashboard, click Enable API option if not done previously.

3. Select Credentials under API Manager and click Create Credentials.

4. select OAuth client ID option.

5. Select the suitable application type for your project and enter any additional information required.

6. If this is the first time creating a client ID, then also required to configure User consent.

  • Provide required information like a product name and support email etc and click Add Scopes option.
  • On the dialog that appears, select the scopes your project uses and click publish button.

7. Then click on Create Client ID

API Implementation

With API Key (Eg: Google Translate)

index.html

<input type="text" id="text" placeholder="Enter text (English)">
<select id="target_lang">
   <option value="af">Afrikaans</option>
   <option value="sq">Albanian</option>
                  ....
   <option value="zu">Zulu</option>
</select>
<input type="button" onclick="gapi.load('client', start)" value="Submit">

<div id="results"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="translate.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>

translate.js

function start() {
      var text=document.getElementById('text').value;
      var t_lang=document.getElementById('target_lang').value;
      gapi.client.init({
           'apiKey': 'YOUR-API-KEY',
           'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/translate/v2/rest'],
      }).then(function() {
           return gapi.client.language.translations.list({
           q: text,
           source: 'en',
           target: t_lang,
       }); }).then(function(response) {
        document.getElementById('results').innerHTML=response.result.data.translations[0].translatedText;
    }, function(reason) {
          document.getElementById('results').innerHTML="Currently not available.!";
          console.log('Error: ' + reason.result.error.message);
     });
 };

Output View

 

With OAuth client ID (Eg: Google Translate)

index.html

<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<div class="col-md-6" style="display: none;" id="contactlist">
    <h2>Contact List</h2>
    <pre id="content"></pre>
</div>
<div id="contactadd" class="col-md-6" style="display: none;">
    <h2> Create new Contact</h2>
    <input type="text" id="contact-name" placeholder="Name"/><br><br>
    <input type="text" id="contact-phone" placeholder="Phone Number"/><br><br>
    <button onclick="CreateContact()">Create</button>
</div>
<script src="people.js"></script>

<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

people.js

// Client ID and API key from the Developer Console
var CLIENT_ID = 'YOUR-CLIENT-ID';
var API_KEY = 'YOUR-API-KEY';

var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"];
var SCOPES = "https://www.googleapis.com/auth/contacts";

var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
var contactadd = document.getElementById('contactadd');
var contactlist = document.getElementById('contactlist');

// On load, called to load the auth2 library and API client library.
function handleClientLoad() {
    gapi.load('client:auth2', initClient);
}

// Initializes the API client library and sets up sign-in state
function initClient() {
    gapi.client.init({
        apiKey: API_KEY,
       clientId: CLIENT_ID,
       discoveryDocs: DISCOVERY_DOCS,
       scope: SCOPES
    }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
    });
}

function CreateContact() {
    var name = document.getElementById('contact-name').value;
    var phone = document.getElementById('contact-phone').value;
    var cphone=phone.charAt(0)=='+'?phone:'+91'+phone;
    gapi.client.people.people.createContact({
          parent: 'people/me',
          'resource': {
          'names': [{
                'givenName':name,
                'displayNameLastFirst':name,
                'displayName': name
          }],
          'phoneNumbers': [{
                   'value': phone,
                   'canonicalForm':cphone
          }]
    }
}).then(function(response) {
          alert("Contact Saved");
          clearList();
          listConnectionNames();
    });
}

// Called when the signed in status changes

function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          contactadd.style.display='block';
          contactlist.style.display='block';
          listConnectionNames();
    } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
          contactadd.style.display='none';
          contactlist.style.display='none';

    }
}

// Sign in the user upon button click.
function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
}

// Sign out the user upon button click.
function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
}

function clearList() {
    var pre = document.getElementById('content');
    pre.innerHTML="";
}


// To append message to UI
function appendPre(message) {
     var pre = document.getElementById('content');
     var textContent = document.createTextNode(message + '\n');
     pre.appendChild(textContent);
}

// Printing name and number
function listConnectionNames() {
     gapi.client.people.people.connections.list({
          'resourceName': 'people/me',
          'pageSize': 300,
          'personFields': 'names,phoneNumbers',
     }).then(function(response) {
          var connections = response.result.connections;
          connections.forEach(function (person) {
                if(person.names && person.names.length > 0){
                      appendPre(person.names[0].displayName+" - "+person.phoneNumbers[0].canonicalForm);
                }
          });
    });
}

Output View

Leave a Reply