Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Google Calendar API with JavaScript

5.00/5 (9 votes)
19 Aug 2015CPOL5 min read 114.6K   3.1K  
A very basic description about Google Calender API to use in your project. This tip will cover API with JavaScript.

Introduction

Google Calendar API is an easiest way to add your Google calendar into your application and manipulate your events and organize meetings, synchronization of calendar in various devices. Here, I will give a basic idea about Google Calendar API with JavaScript. For example, you could develop a web application to create or display Calendar data, or a desktop application that synchronizes a user's Calendar with an existing desktop application. Your app could be a device that brings the Calendar experience to a new platform.

NOTE: The concept of this article is from Google Calendar API documentation provided by Google itself. Here, those concepts are defined in an easy manner for beginners.

Image 1

Background

GoogleAPIs

As we know, Google makes our life easier by providing many APIs. These APIs are useful in their own way, Here, I am explaining one of the APIs from Google which is Google Calendar API. The Google Calendar API allows a program to perform many of the operations available via Google Calendar web interface. Using this API, it is possible to search for and view public calendar events. Authenticated sessions can access private calendars, as well as create, edit, and delete both events and the calendars that contain them.

In this article, you will find step by step integration with Google calendar API with your application. Here, implementation in done with the current version: Google Calendar API V3.


Prerequisites

  • Get a Google Account.
  • Get familiar with Google Calendar (as a user).
  • Get familiar with Google Developers Console.
  • Basic knowledge of REST (REpresentational State Transfer).
  • Basic knowledge of JSON data format.
  • Create an API key and ClientID to identify app.
  • Activate Calendar API.
  • Manage projects, billing, quota if paid API.
  • Credentials, access, security, and identity
  • ?oAuth 2.0 ClientID
  • ?API Key (Server or Browser)

Let's get familiar with Google Developers Console and its product

Google has provided all documentation for Developer Console and how to use it. It's not needed to redo all steps to interact with Google products but here you can have an overview of things to start with.

First, go here to see the listing of all the products provided by Google for a developer. Now as we are only interested here for Calendar API, look for that on the page and click on it. It will redirect you to Calendar API documentation.

On the left panel, you will see a list of various languages in which you can build your code. But here, it's JavaScript description, so click on JavaScript. You will see a complete documentation for developing a sample app.

Also, you can see on the left panel under "Use the Calendar API" section how to Authorize your application with OAuth 2.0. It's a step by step guideline and a very easy implementation. Whenever you create an application, you need to register it on Google Developers Console (https://console.developers.google.com/). This link will ask you to sign in.

After successful sign- in, on the left side, you can see all the options available for you.

Image 3

When you finish with managing your console, please note down OAuth ClientID and API key, these are going to be used in your application.

You can use an OAuth 2.0 client ID to generate an access token. The token contains a unique identifier.

OR

An API key, Using an API key does not require user action or consent. API keys do not grant access to any account information, and are not used for authorization.

Use API key for application where data that has been identified as public, such as a public calendar or public blog means that information which is public by owner. Or it may be owned by a Google service such as Google Maps or Google Translate.


API Request Using the JavaScript Client Library

Image 4

The common way to use the JavaScript client library to make API requests:

  1. The application loads the JavaScript client library.
  2. The application references its API key, which authenticates the application with Google services.
  3. If the application needs access to the user's personal information, it opens a session with a Google auth server. The auth server opens a dialog box which prompts the user to authorize the use of personal information.
  4. The application loads the API for the Google service.
  5. The application initializes a request object (also called a service object) that specifies the data to be returned by the API.
  6. The application executes the request and processes the data returned by the API.

Calendar Concepts

Google Calendar is built on several basic concepts which are useful during implantation. Google also provided the whole documentation for calendar concepts and its use cases here.

I have summed it up into a diagram for easy understanding.

CalendarConcepts


Google Calendar API Model

API reference is organized by resource type. Each resource type has one or more data representations and one or more methods. See this link.

Image 6

Resources and Collection further have methods which directly can be used with API call. See this link.

Image 7


How the Application Interacts with Google

Image 8


Using the Code

Basically, whatever we have setup in Google Developer Console, now we are going to use it in our application. This example is similar as used by Google Documentation.

In HTML page, under script section, add the following lines. ClientID and ApiKey are responsible for talking with Google database.

HTML
// Google api console clientID and apiKey 

 var clientId = '252751we734600-se6610ol8twerwern886jj7gc5m2ugaai.apps.googleuserecontent.com';
 var apiKey = 'AIzaSyCnk5CDEX3Pvwerwerwe0OpnVf4eW_Lmeere80';

 // enter the scope of current project (this API must be turned on in the Google console)
   var scopes = 'https://www.googleapis.com/auth/calendar';


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

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

// This is the resource we will pass while calling api function
var resource = {
            "summary": "My Event",
            "start": {
                "dateTime": today
            },
            "end": {
                "dateTime": twoHoursLater
            },
            "description":"We are organizing events",
            "location":"US",
            "attendees":[
            {
                    "email":"attendee1@gmail.com",
                    "displayName":"Jhon",
                    "organizer":true,
                    "self":false,
                    "resource":false,
                    "optional":false,
                    "responseStatus":"needsAction",
                    "comment":"This is my demo event",
                    "additionalGuests":3
                    
            },
            {    
                "email":"attendee2@gmail.com",
                    "displayName":"Marry",
                    "organizer":true,
                    "self":false,
                    "resource":false,
                    "optional":false,
                    "responseStatus":"needsAction",
                    "comment":"This is an official event",
                    "additionalGuests":3
            }
            ],
        };

function makeApiCall(){
gapi.client.load('calendar', 'v3', function () { // load the calendar api (version 3)
                var request = gapi.client.calendar.events.insert
                ({
                    'calendarId': '24tn4fht2tr6m86efdiqqlsedk@group.calendar.google.com', 
// calendar ID which id of Google Calendar where you are creating events. this can be copied from your Google Calendar user view.

                    "resource": resource 	// above resource will be passed here
                });                
}

On html page, display calendar using frame. This iframe is available for you on Google Calendar User interface. It will keep syncing your calendar in Your App as well in Google account or any other associate device.

HTML
<button id="btnCreateEvents" class="btn btn-primary" onclick="makeApiCall();">
                    Create Events</button>  

<div id="divifm">
                    <iframe id="ifmCalendar" 
                    src="https://www.google.com/calendar/embed?
                    height=550&amp;wkst=1&amp;bgcolor=%23FFFFFF&
                    amp;src=24tn4fht2sssdssfdiqqlsedk%40group.calendar.google.com&
                    amp;color=%238C500B&amp;ctz=Asia%2FCalcutta"
                        style="border-width: 0" width="950" 
                        height="520" frameborder="0" scrolling="no">
                    </iframe>
                </div>

Your application will look like this:

Image 9

I have the entire code attached. You can download and work on it. Here, I just highlighted the areas which are important to take care while communicating with API.

Calendar Settings: You can customize your calendar using interface in Google Calendar as follows:

Image 10

Points of Interest

I have learned how to use Google APIs after using this calendar API integration. I described everything which is already available but in different places. While learning, I spent a lot of time combining these concepts. I am posting here to save your time on the same thing.

Any Questions?

If you have any questions, please feel free to ask.

Thanks!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)