Fetch and create events in Google Calendar with HTML and Javascript.

The Google Calendar API is a RESTful API that can be accessed via explicit HTTP calls or the Google Client Library. The API demonstrates most of the features available in the Google Calendar web interface.

This blog is a step-by-step guide on how to build a simple website using only HTML and JavaScript where users can receive their calendar events and create new events.

google calendar api

To read events from your public Google Calendar you will need to create a Google API Key which first requires you to have a Google Account. After that you need to go through the following steps to get the API key and other required key pair values.

  1. Create Project Click on this link to create a new project.

  2. Enable API Visit this link and enable your Google Calendar API. Make sure your recently created project is selected. enable api

  3. After that navigate to the Credentials tab and click on CREATE CREDENTIALS and select API Key from the dropdown. After which an API key will be generated for you.
    build credibility

  4. select next OAuth consent screen Go to tab and select user type as external.

  5. You will be asked about app information. Give the appropriate app name and support email and click Save and Continue. Refresh the page and click on PUBLISH APP NOW
    publish app

  6. Now again go to Credentials tap and now create OAuth Client ID. Select Application Type as Web Application and then authorize your domain URL on which your project will be running (If your on development server then give your localhost and the port on which project is running). You will now have your Client ID and Client Secret which we will use for configuration later.
    OAuth Client ID

Integrating Website with Google Calendar API

Now we have the API Key as well as the Client ID so we are ready to dive into the coding.

receive events

  1. Create a folder, inside which create an HTML file and a JS file. Open folder with VS Code and run it using live server index.html,

  2. Add the following code to your index.html

    <!DOCTYPE html>
    <html>
    <head>
    <title>Google Calendar API Quickstart</title>
    <meta charset="utf-8" />
    </head>
    <body>
    <p>Google Calendar API Quickstart</p>
    
    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
    <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
    <pre id="content" style="white-space: pre-wrap;"></pre>
    <script src="https://dev.to/debopriyadey/./index.js" type="text/javascript"></script>
    <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
    <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
    </body>
    </html>
    
  3. Add the following code to your index.js, To change <YOUR_CLIENT_ID> with client id and <YOUR_API_KEY> With API Key. You can find them with your Google Calendar API credentials

      /* exported gapiLoaded */
      /* exported gisLoaded */
      /* exported handleAuthClick */
      /* exported handleSignoutClick */
    
      // TODO(developer): Set to client ID and API key from the Developer Console
      const CLIENT_ID = '<YOUR_CLIENT_ID>';
      const API_KEY = '<YOUR_API_KEY>';
    
      // Discovery doc URL for APIs used by the quickstart
      const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
    
      // Authorization scopes required by the API; multiple scopes can be
      // included, separated by spaces.
      const SCOPES = 'https://www.googleapis.com/auth/calendar';
    
      let tokenClient;
      let gapiInited = false;
      let gisInited = false;
    
      document.getElementById('authorize_button').style.visibility = 'hidden';
      document.getElementById('signout_button').style.visibility = 'hidden';
    
      /**
       * Callback after api.js is loaded.
       */
      function gapiLoaded() {
        gapi.load('client', initializeGapiClient);
      }
    
      /**
       * Callback after the API client is loaded. Loads the
       * discovery doc to initialize the API.
       */
      async function initializeGapiClient() {
        await gapi.client.init({
          apiKey: API_KEY,
          discoveryDocs: [DISCOVERY_DOC],
        });
        gapiInited = true;
        maybeEnableButtons();
      }
    
      /**
       * Callback after Google Identity Services are loaded.
       */
      function gisLoaded() {
        tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: CLIENT_ID,
          scope: SCOPES,
          callback: '', // defined later
        });
        gisInited = true;
        maybeEnableButtons();
      }
    
      /**
       * Enables user interaction after all libraries are loaded.
       */
      function maybeEnableButtons() {
        if (gapiInited && gisInited) {
          document.getElementById('authorize_button').style.visibility = 'visible';
        }
      }
    
      /**
       *  Sign in the user upon button click.
       */
      function handleAuthClick() {
        tokenClient.callback = async (resp) => {
          if (resp.error !== undefined) {
            throw (resp);
          }
          document.getElementById('signout_button').style.visibility = 'visible';
          document.getElementById('authorize_button').innerText="Refresh";
          await listUpcomingEvents();
        };
    
        if (gapi.client.getToken() === null) {
          // Prompt the user to select a Google Account and ask for consent to share their data
          // when establishing a new session.
          tokenClient.requestAccessToken({prompt: 'consent'});
        } else {
          // Skip display of account chooser and consent dialog for an existing session.
          tokenClient.requestAccessToken({prompt: ''});
        }
      }
    
      /**
       *  Sign out the user upon button click.
       */
      function handleSignoutClick() {
        const token = gapi.client.getToken();
        if (token !== null) {
          google.accounts.oauth2.revoke(token.access_token);
          gapi.client.setToken('');
          document.getElementById('content').innerText="";
          document.getElementById('authorize_button').innerText="Authorize";
          document.getElementById('signout_button').style.visibility = 'hidden';
        }
      }
    
      /**
       * Print the summary and start datetime/date of the next ten events in
       * the authorized user's calendar. If no events are found an
       * appropriate message is printed.
       */
      async function listUpcomingEvents() {
        let response;
        try {
          const request = {
            'calendarId': 'primary',
            'timeMin': (new Date()).toISOString(),
            'showDeleted': false,
            'singleEvents': true,
            'maxResults': 10,
            'orderBy': 'startTime',
          };
          response = await gapi.client.calendar.events.list(request);
        } catch (err) {
          document.getElementById('content').innerText = err.message;
          return;
        }
    
        const events = response.result.items;
        if (!events || events.length == 0) {
          document.getElementById('content').innerText="No events found.";
          return;
        }
        // Flatten to string to display
        const output = events.reduce(
            (str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
            'Events:\n');
        document.getElementById('content').innerText = output;
      }
    
  4. run index.html With Live Server on VS Code. It should appear.
    authorized

  5. After clicking on authorize button a popup will appear. You will be asked to authorize your Google Account. All upcoming events from that event’s calendar will be visible after you authorize your account. (You can pre-schedule some events for testing)

planning

So far we have successfully received the calendar event now we need to create the event from our website.

create event

  1. First we have to create a form in our index.html,

    <form id="event_form">
    <fieldset>
      <input type="text" name="title" id="title" placeholder="Add Title" class="input-title" />
      <br />
      <textarea type="text" name="desc" id="desc" placeholder="Add Descreption" class="input-title"></textarea>
      <br />
      <label>Date</label>
      <input type="date" name="date" id="date" />
      <div>
        <label>Start Time</label>
        <input type="time" name="st" id="st" />
        <label>End Time</label>
        <input type="time" name="et" id="et" />
      </div>
      <button type="button" onclick="addEvent()">Schedule</button>
    </fieldset>
    </form>
    
  2. Add the AddEvent function to your index.js, Also make sure your SCOPE https://www.googleapis.com/auth/calendar,

const addEvent = () => {
  const title = document.getElementById("title").value;
  const desc = document.getElementById("desc").value;
  const date = document.getElementById("date").value;
  const start = document.getElementById("st").value;
  const end = document.getElementById("et").value;

  const startTime = new Date(date + "," + start).toISOString();
  const endTime = new Date(date + "," + end).toISOString();

  var event = {
    summary: title,
    location: "Google Meet",
    description: desc,
    start: {
      dateTime: startTime,
      timeZone: "America/Los_Angeles"
    },
    end: {
      dateTime: endTime,
      timeZone: "America/Los_Angeles"
    },
    recurrence: ["RRULE:FREQ=DAILY;COUNT=2"],
    attendees: [
      { email: "abc@google.com" },
      { email: "xyz@google.com" }
    ],
    reminders: {
      useDefault: false,
      overrides: [
        { method: "email", minutes: 24 * 60 },
        { method: "popup", minutes: 10 }
      ]
    }
  };

  console.log(event)
  var request = gapi.client.calendar.events.insert({
    calendarId: "primary",
    resource: event
  });

  request.execute(function(event) {
    console.log(event.htmlLink);
  });
};
enter fullscreen mode

exit fullscreen mode

this should be your end result
Final result

By now you have built a basic website where users can list their calendar events and add new events as well. I pushed my code to this GitHub repo You can fork it and add your innovations or if you want to contribute to this repository you can create a pull request.
Also share your websites in the comment section if you are still facing any problem then you can comment below I will try to solve it.

Reference

Leave a Comment