Using the new JS library to unlock the power of Google Apps

Thursday, December 1, 2011 | 1:58 PM

Labels: , , ,

Yesterday, the Google APIs Client Library for JavaScript was released, unlocking tons of possibilities for fast, dynamic web applications, without requiring developers to run their own backend services to talk to Google APIs. This client library supports all discovery-based APIs, including the Google Tasks, Google Calendar v3 and Groups Settings APIs. To make it easy to get started using the JS client with Google Apps APIs, we’ve provided an example below.

After you’ve configured your APIs console project as described in the client library instructions, grab a copy of your client ID and API key, as well as the scopes you need to access the API of your choice.

var clientId = 'YOUR_CLIENT_ID';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/calendar';

You’ll also need several boilerplate methods to check that the user is logged in and to handle authorization:

function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth,1);
  checkAuth();
}

function checkAuth() {
  gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true},
      handleAuthResult);
}

function handleAuthResult(authResult) {
  var authorizeButton = document.getElementById('authorize-button');
  if (authResult) {
    authorizeButton.style.visibility = 'hidden';
    makeApiCall();
  } else {
    authorizeButton.style.visibility = '';
    authorizeButton.onclick = handleAuthClick;
   }
}

function handleAuthClick(event) {
  gapi.auth.authorize(
      {client_id: clientId, scope: scopes, immediate: false},
      handleAuthResult);
  return false;
}

Once the application is authorized, the makeApiCall function makes a request to the API of your choice. Here we make a request to retrieve a list of events from the user’s primary calendar, and use the results to populate a list on the page:

function makeApiCall() {
  gapi.client.load('calendar', 'v3', function() {
    var request = gapi.client.calendar.events.list({
      'calendarId': 'primary'
    });
          
    request.execute(function(resp) {
      for (var i = 0; i < resp.items.length; i++) {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(resp.items[i].summary));
        document.getElementById('events').appendChild(li);
      }
    });
  });
}

To tie all of this together, we use the following HTML, which configures the DOM elements we need to display the list, a login button the user can click to grant authorization, and a script tag to initially load the client library:

<html>
  <body>
    <div id='content'>
      <h1>Events</h1>
      <ul id='events'></ul>
    </div>
    <a href='#' id='authorize-button' onclick='handleAuthClick();'>Login</a>
    
    <script>
      // Insert the JS from above, here.
    </script>
    <script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
  </body>
</html>

Making requests to other discovery-based APIs, such as the Tasks API requires only small modifications to the above:

  1. Replace the contents of the scopes variable to use the appropriate scope for the other API.
  2. Modify makeApiCall to load the appropriate API and version.
  3. Modify request (and the execute callback) to load a different API method and handle the response.

As additional discovery-based APIs are released, they’ll be automatically supported by the library (just like the Python and Ruby clients).

If you have general questions about the JS client, check out the JavaScript client group. For questions on specific Apps APIs come find us in the respective Apps API forum.


Dan Holevoet   profile

Dan joined the Google Developer Relations team in 2007. When not playing Starcraft, he works on Google Apps, with a focus on the Calendar and Contacts APIs. He's previously worked on iGoogle, OpenSocial, Gmail contextual gadgets, and the Google Apps Marketplace.

14 comments:

Bog Imp said...

Pls, Include Ability to Upload Files directly from Javascript to Google Docs.

Kyaw Tun said...

Is it safe to leave apiKey in JS?

Anonymous said...

I need to turn on my cookies

Dan Holevoet said...

The apiKey is used in conjunction with designated referrers, which you must declare in the APIs Console. If the key is sent from an unauthorized referrer, it will not work. You should make your accepted referrer list as limited as possible to ensure that others do not use your apiKey for their own requests.

Srini said...

how can you use this in google sites?

Swap said...

I am running your code but it is not working i have replaced your client id and api key with my api key and client id nothing happens when i am clicking login button .. Please help

Tomino said...

I think I did everything as described (Client id, api key, example html with js code) but it does not work. Javascript console says: "Unable to post message to file://. Recipient has origin null.
core:rpc:shindig.random:shindig.sha1.js:814"

I am so new in this that I do not know where to start to fix this. Any suggestion what went wrong and how to fix it?

Yahya Akhter said...

hey i need help from you . how to set sendNotifications parameter by using js libraris.to send notifications to atndees. for know i can insert events but notification could not sent to atendees

erie said...

Hi Dan,
I am trying to access the calendar from a phonegap app so I got a client id for installed applications. I noticed that when the app tries to authenticate the user through oauth2.0, it assigns as origin the "file://" which is not the case. How can I fix this? Thank you very much in advance!

John Kennedy said...

Hi Dan,

I'm using a bunch of this code verbatim in an app I'm writing. Is there any particular way you would like to be cited or a licence I should refer to?

Jean-Louis curty said...

Hi,
do you have an example for installed applications with refresh token ?
it's difficult to find javascript examples,
thanks,
jl

Javier Arellano said...

Thank you for your post, it helped me a lot!

Thomas K├Ânig said...

Thanks a lot man! You made my day :-)

Li Z. said...

I have exact problem as 'Tomino" stated. I provided valid value for clientId and apiKey. I got error 'Unable to post message to file://. Recipient has origin null. core:rpc:shindig.random:shindig.sha1.js:970".

Do I missing anything? Thanks for help.