How to Use the Google Calendar API

Bryan Helmig
Bryan Helmig / December 1, 2018

Google Calendar is one of the most popular ways to manage events, meetings, holidays, and anything else you need to schedule. The Google Calendar API lets you add and update events automatically, so your computer manage your calendar for you!

Here's everything you need to know about the Google Calendar API:


How to Get Started With the Google Calendar API?

There are three primary ways ways to use the Google Calendar API:

Option 1: Google Calendar Official Client Libraries

Google provides official libraries across many popular languages like Java, Javascript, Python, PHP and more. A full list of available client libraries can be found on the Google Calendar documentation download page here . This may require more installation steps.

How Do You Use the Official Client Library?

Here's an example of using the Google Calendar official Python client library:

from googleapiclient.discovery import build
from oauth2client import file, client
credentials = client.AccessTokenCredentials('ACCESS_TOKEN', 'USER_AGENT')
service = build('calendar', 'v3', credentials=credentials)
calendars = service.calendarList().list().execute()

When Should I Use the Official Client Libraries?

If you are a developer with control over your environment (and especially can install new libraries), the official libraries will make it far quicker to start using the Google Calendar API.If you need more complex logging, or already have powerful HTTP client integration, you might prefer the Native HTTP APIs.

Estimated time to build a basic integration with the official client libraries: 12 hours.

Option 2: Native Google Calendar HTTP APIs

Most programming languages provide HTTP clients that you can use to make your own HTTP calls to the API. In fact, the official client libraries often use them behind the scenes. You'll have to set your own API key, headers, and other HTTP settings which can be cumbersome, but usually that is a very routine task. Once you write code to make a single API call, you can reuse it for later API calls.

How Do You Use Google Calendar's Native HTTP API?

Here's an example of using Google Calendar's native HTTP API in Python using the popular requests library, it grabs a list of calendars in your account:

import requests
response = requests.get(
    url='https://www.googleapis.com/calendar/v3/users/me/calendarList',
    headers={'Authorization': 'Bearer ACCESS_TOKEN'},
)
response.raise_for_status()
calendars = response.json().get('items')

When Should I Use the Native HTTP API?

If you are a developer and are comfortable with your programming language's standard library HTTP client, or have a favorite HTTP client in mind, the native HTTP API might provide a better experience. If you have other special needs like logging, HTTP proxies, and asynchronousness, the native HTTP API may be the only option that let you customize Google Calendar's API calls to work the way you need.

Estimated time to build a basic integration with the native HTTP APIs: 15 hours.

Option 3: Use Zapier

Whether you're a developer or not, Zapier's app integration platform can often do much of what the official client libraries or native HTTP APIs can do—without needing to write code. Zapier is an easy-to-use UI to build workflows that seamlessly incorporate data from other APIs and services. You can use Google Calendar's core API calls through Zapier with 1,300+ other APIs—perfect for workflows between popular SaaS services. Here are some popular examples:

How Do You Use Google Calendar's API With Zapier?

Zapier makes it easy to use Google Calendar's API. Connect your Google Calendar account to Zapier using Google's OAuth-powered authentication, then you can select from triggers or actions to watch Google Calendar for new data or find and create data in Google Calendar.

When should I use Zapier instead of the APIs?

Generally speaking, it can be both time and cost effective to use Zapier to create Google Calendar automations instead of writing them yourselves. Zapier allows for deep customizability and flexibility, with thousands of popular integrations, filters and formatters to get the data you need, and tools to add Python or Javascript code to your workflows

The time savings is particularly noticeable if you need to integrate multiple APIs with their own idiosyncrasies. It's additionally helpful if others on your team might need to change the automation later, especially colleagues who are not developers. You won't have to maintain the integration, either—if Google Calendar changes their API calls, Zapier's team will keep its integrations updated so your workflows will keep working. Zapier makes sharing and maintenance of your API-powered workflows a breeze.

Estimated time to build a basic integration with Zapier: 10 minutes.

Try Zapier with Google Calendar for free!


How to Create Google Calendar Access Tokens or API keys?

How to Create a Temporary Google Calendar Access Token

Want to test out using the Google Calendar API? You can use the Google OAuth 2.0 Playground to create access tokens that only work for an hour which is useful for initial testing without going through all the steps to create a project (which can be complicated).

First, select the API you want access to. In this case, we just need Calendar access:

Second, you'll click Authorize APIs, you'll be redirected to an approval screen. Choose your account, then click allow and continue. Next, you'll want to exchange the Authorization code for access and refresh tokens:

Thirdly, now you should see provided access tokens and refresh tokens:

Finally, you'll see this access token starts with abc1..., so let's copy that! Unfortunately, we have no use for this particular refresh token (since you do not have Google's own client_secret, it cannot be used outside of this tool).

Important! These only work for an hour, so this is only for testing / playing around. You must repeat these steps to get a new access token every hour.

How to Create a Full Google Calendar Access Token?

Creating a full Google Calendar access token is a bit more complicated, but is required if you want to build a full project with Google Calendar's API.

First, create a project within Google's Cloud dashboard. If you already have a project, you can skip this part and use the existing project:

Second, once you are in your project, go the dashboard and click the Enable APIs button:

Third, search for Google Calendar and enable it if you haven't already:

Fourth, once it is enabled, create the 'OAuth Client ID' credential from the left sidebar:

Fifth, you will likely need to configure your consent screen, so make sure to give it a descriptive name and select Google Calendar for the scopes:

Sixth, now you'll be able to finalize your client, choose 'Web Application' for Application Type and be sure to give it a descriptive name like 'My Calendar Client':

Finally, you'll be given a 'Client ID' and 'Client Secret', keep those handy for the next steps!

You now have two options and which next step you choose depends on your needs:

  • Building an application for others: you'll need to get familiar with the standard Google OAuth flow. This will involved a web server and is just like building out any OAuth application.
  • Building an application hardcoded for yourself: you can use Google's OAuth 2.0 Playground to generate a refresh token with your own application without additional web services. Read on to learn how!

A clever way to get a personal access token and refresh token click into your 'My Calendar Client' from the last step and add https://developers.google.com/oauthplayground to the 'Authorized redirect URIs':

Just like the 'Creating a Temporary Access Token' section, we're going to use the Google OAuth 2.0 Playground but we're going to provide our own 'Client ID' and 'Client Secret' from before:

Now you can follow the same steps as before to exchange for tokens, but this time take note of your refresh token! While your access token is still only good for an hour, your refresh token is actually useful and you can use it to get a new access token.


How to Make Your First Google Calendar API Call?

You'll need an ACCESS_TOKEN to complete this request!

To make your API call, it is best to take stock of all the components you'll need to make that request. First we need our target (why are we making the API call?), then we need our authorization (how will we connect to our account via the API?), and finally need to think about anything else the request might require (what data fields will we need from the API or should we send to the API?).

Let's start with one of the simplest Google Calendar API calls you can make: Get Calendar settings. This is just to ensure our API key works properly:

  • Method: GET
  • URL: https://www.googleapis.com/calendar/v3/users/me/settings
  • Querystring: none
  • Headers:
  • Authorization: Bearer abc1.aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789aBc
  • Content-Type: application/json
  • Body: not applicable for GET

Let's try this example of the official client libraries using Python Google's google-api-python-client and oauth2client:

from googleapiclient.discovery import build
from oauth2client import file, client
credentials = client.AccessTokenCredentials(
    'ACCESS_TOKEN',
    'my-calendar-bot/1.0',
)
service = build('calendar', 'v3', credentials=credentials)
settings = service.settings().list().execute()
print(settings)

Or, here's an example of the native REST API using Python and the popular requests library:

import requests
response = requests.get(
    url='https://www.googleapis.com/calendar/v3/users/me/settings',
    headers={
        'Authorization': 'Bearer ACCESS_TOKEN',
    },
)
response.raise_for_status()
print(response.json())

Prefer Javascript? Here's an example of Google Calendar's native REST API using Javascript and the popular fetch function:

var fetch = require("node-fetch"); // or fetch() is native in browsers
fetch("https://www.googleapis.com/calendar/v3/users/me/settings", {
  method: "get",
  headers: {
    Authorization: "Bearer ACCESS_TOKEN"
  }
})
  .then(res => res.json())
  .then(json => console.log(json));

Or, you could do the same thing with the native REST API using Java and the easy to use OkHttp library:

OkHttpClient client = new OkHttpClient();

url = HttpUrl
    .parse("https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events")
    .newBuilder();
url.addQueryParameter("q", "SEARCH_TERM");

Request request = new Request.Builder()
    .url(url.build().toString())
    .get()
    .addHeader("Authorization", "Bearer ACCESS_TOKEN")
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

Congrats! It works!


How to Refresh Your Google Calendar Access Token Using Refresh Tokens

You'll need an ACCESS_TOKEN, CLIENT_ID, and CLIENT_SECRET to complete this request!

Eventually your access token will expire, but luckily you can use your client_id, client_secret, and refresh_token together to get a brand new access_token. To refresh your access token you'll need to make a POST request to https://www.googleapis.com/oauth2/v4/token with the grant_type=refresh_token payload and use the newly returned tokens.

Let's try this example of the official client libraries using Python Google's google-api-python-client and oauth2client:

from googleapiclient.discovery import build
import httplib2
from oauth2client import file, client, GOOGLE_TOKEN_URI
credentials = client.GoogleCredentials(
    # technically acces token could be an empty string
    'ACCESS_TOKEN',
    'CLIENT_ID',
    'CLIENT_SECRET',
    'REFRESH_TOKEN',
    None,  # this is token_expiry, we can leave it None
    GOOGLE_TOKEN_URI,
    'my-calendar-bot/1.0'
)
credentials.refresh(httplib2.Http())
print(credentials.access_token)
# or use in later build(..., credentials=credentials)

Or, here's an example of the native REST API using Python and the popular requests library to update the refresh token:

import requests
response = requests.post(
    url='https://www.googleapis.com/oauth2/v4/token',
    data={
        'client_id': 'CLIENT_ID',
        'client_secret': 'CLIENT_SECRET',
        'refresh_token': 'REFRESH_TOKEN',
        'grant_type': 'refresh_token',
    },
    headers={
        'Content-Type': 'application/x-www-form-urlencoded',
    },
)
response.raise_for_status()
print(response.json().get('access_token'))

Here's one more example of the REST API using Javascript and the popular fetch function:

var fetch = require("node-fetch"); // or fetch() is native in browsers

var makeQuerystring = params =>
  Object.keys(params)
    .map(key => {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    })
    .join("&");

fetch("https://www.googleapis.com/oauth2/v4/token", {
  method: "post",
  body: makeQuerystring({
    client_id: "CLIENT_ID",
    client_secret: "CLIENT_SECRET",
    refresh_token: "REFRESH_TOKEN",
    grant_type: "refresh_token"
  }),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  }
})
  .then(res => res.json())
  .then(json => console.log(json));

And here is a final version of the native REST API with Java and the common OkHttp library:

OkHttpClient client = new OkHttpClient();

url = HttpUrl
    .parse("https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events")
    .newBuilder();
url.addQueryParameter("q", "SEARCH_TERM");

Request request = new Request.Builder()
    .url(url.build().toString())
    .get()
    .addHeader("Authorization", "Bearer ACCESS_TOKEN")
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

Now you can use the returned access_token going forward.


How to Find a Calendar With the Google Calendar API?

You'll need an ACCESS_TOKEN, and CALENDAR_NAME to complete this request!

If you want to automatically create events in Google Calendar, you'd first need a way to find the calendars on your account. The best way to find calendars is by searching through the calendars returned from https://www.googleapis.com/calendar/v3/users/me/calendarList API endpoint. Below is an example of how to find calendars via the Google Calendar API with Python and the popular requests library:

import requests
response = requests.get(
    url='https://www.googleapis.com/calendar/v3/users/me/calendarList',
    headers={
        'Authorization': 'Bearer ACCESS_TOKEN',
    },
)
response.raise_for_status()

calendar_id = None
for calendar in response.json().get('items'):
    if calendar['summary'] == 'CALENDAR_NAME':
        calendar_id = calendar['id']
        break

print(calendar_id)

Or, you could find calendars with Google Calendar's REST API using Javascript and the popular fetch function:

var fetch = require("node-fetch"); // or fetch() is native in browsers
fetch("https://www.googleapis.com/calendar/v3/users/me/calendarList", {
  method: "get",
  headers: {
    Authorization: "Bearer ACCESS_TOKEN"
  }
})
  .then(res => res.json())
  .then(json => {
    for (var calendar of json.items) {
      if (calendar.summary === 'CALENDAR_NAME') {
        var calendarId = calendar.id;
        break;
      }
    }
    console.log(calendarId);
  );

Or, you could do it with the native REST API using Java and the popular OkHttp library:

OkHttpClient client = new OkHttpClient();

url = HttpUrl
    .parse("https://www.googleapis.com/calendar/v3/users/me/calendarList")
    .newBuilder();
Request request = new Request.Builder()
    .url(url.build().toString())
    .get()
    .addHeader("Authorization", "Bearer ACCESS_TOKEN")
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

How to Create a New Event in Google Calendar API?

You'll need an ACCESS_TOKEN, EVENT_TEXT, and ACCESS_TOKEN to complete this request!

Now that you can look up existing calendars, you could also create new events in that calendar through Google Calendar's API. The easiest way to create a new event with the Google Calendar API is by sending a POST request to the quickAdd endpoint with a text=Tuesday+meet+Bob! body – this includes intelligent parsing of times for simple scheduling. Here's one way using the native REST API through Python and the popular requests library:

import requests
response = requests.post(
    url='https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events/quickAdd',
    data={
        'text': 'EVENT_TEXT',
    },
    headers={
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ACCESS_TOKEN',
    },
)
response.raise_for_status()
print(response.json())

Or here's how to add events with the REST API using Javascript and the popular fetch function:

var fetch = require("node-fetch"); // or fetch() is native in browsers

var makeQuerystring = params =>
  Object.keys(params)
    .map(key => {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    })
    .join("&");

fetch(
  "https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events/quickAdd",
  {
    method: "post",
    body: makeQuerystring({
      text: "EVENT_TEXT"
    }),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization: "Bearer ACCESS_TOKEN"
    }
  }
)
  .then(res => res.json())
  .then(json => console.log(json));

Alternatively, if you are using Java, you might prefer the very popular OkHttp library with the native REST APIU:

body = new FormBody.Builder()
    .add("text", "EVENT_TEXT")
    .build();

url = HttpUrl
    .parse("https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events/quickAdd")
    .newBuilder();
Request request = new Request.Builder()
    .url(url.build().toString())
    .post(body)
    .addHeader("Authorization", "Bearer ACCESS_TOKEN")
    .addHeader("Content-Type", "application/x-www-form-urlencoded")
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

How to Find an Event in the Google Calendar API?

You'll need an ACCESS_TOKEN, CALENDAR_ID, and SEARCH_TERM to complete this request!

You might also want to see if an event exists before creating one. The best way to look for events in the Google Calendar API is by sending a GET request to the https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events endpoint with a ?q=word querystring and looking through the results. This is easy with the native REST API using Python and the popular requests library:

import requests
response = requests.get(
    url='https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events',
    params={
        'q': 'SEARCH_TERM',
    },
    headers={
        'Authorization': 'Bearer ACCESS_TOKEN',
    },
)
response.raise_for_status()
print(response.json())

Or, you could do it with the native REST API using Javascript and the popular fetch function:

var fetch = require("node-fetch"); // or fetch() is native in browsers

var makeQuerystring = params =>
  Object.keys(params)
    .map(key => {
      return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
    })
    .join("&");

var url = "https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events";
var querystring = makeQuerystring({
  q: "SEARCH_TERM"
});

fetch(url + "?" + querystring, {
  method: "get",
  headers: {
    Authorization: "Bearer ACCESS_TOKEN"
  }
})
  .then(res => res.json())
  .then(json => console.log(json));

Or, you could do it with the native REST API using Java and the popular OkHttp library:

OkHttpClient client = new OkHttpClient();

url = HttpUrl
    .parse("https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events")
    .newBuilder();
url.addQueryParameter("q", "SEARCH_TERM");

Request request = new Request.Builder()
    .url(url.build().toString())
    .get()
    .addHeader("Authorization", "Bearer ACCESS_TOKEN")
    .build();

Response response = client.newCall(request).execute();
System.out.println(response.body().string());

Where to go next with the Google Calendar API?

We recommend going to the Official Google Calendar API Reference to see all the endpoints you might want to use.

Remember, you can avoid deploying your own code and use Zapier to build Google Calendar integrations, and you can even use Python and Javascript in web workflows and automations with zero-deployments as well!


Load Comments...

Comments powered by Disqus