DEV Community

Peter Jacxsens
Peter Jacxsens

Posted on • Updated on

using google-api-javascript-client (gapi) with no authentication [code example]

Here is an example of using Google APIs Client Library for browser JavaScript, aka gapi with no authentification. The Google Api we are calling here is Calendar API.

There are some caveats:

  • We will be calling a public calendar.
  • It's a read-only request.
  • You do need an api key from google cloud console.

First load api.js: <script src="https://apis.google.com/js/api.js"></script>. Then add the following script:

  // fill in your api key
  const apiKey = "******";
  // select a calendar by id
  const calendarId = "******";

  function start() {
    // Initializes the client with the API key and the Calendar API.
    gapi.client.init({
      'apiKey': apiKey,
      // load the correct library (calendar in this case)
      'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
      'scopes': 'https://www.googleapis.com/auth/calendar.readonly'
    }).then(function() {
      return gapi.client.calendar.events.list({
        'calendarId': calendarId,
        'maxResults' : 5,
      });
    }).then(function(response) {
      console.log('response',response.result.items);
    }, function(reason) {
      console.log('Error: ', reason);
    });
  };
  // Loads the JavaScript client library and invokes `start` afterwards.
  gapi.load('client', start);
Enter fullscreen mode Exit fullscreen mode

This example is based on a sample in the google-api-javascript-client: https://github.com/google/google-api-javascript-client/blob/master/docs/samples.md#loading-an-api-and-making-a-request.

Top comments (0)