Hide
Google Calendar API

Configure your App

You must instantiate a client to make requests to the API. All requests to the Google Calendar API require authorization.

The following code demonstrates how to configure an authorized service object using OAuth 2.0 for native applications. For more information, see Authorize Requests.

To find your project's client ID and client secret, do the following:

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the Google Calendar API.
  4. In the sidebar on the left, select Credentials.
  5. If you haven't done so already, create your project's OAuth 2.0 credentials by clicking Create new Client ID, and providing the information needed to create the credentials.
  6. Look for the Client ID and Client secret in the table associated with each of your credentials.

Note that not all types of credentials use both a client ID and client secret and won't be listed in the table if they are not used.

Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.calendar.Calendar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;

...

  public void setUp() throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    // The clientId and clientSecret can be found in Google Developers Console
    String clientId = "YOUR_CLIENT_ID";
    String clientSecret = "YOUR_CLIENT_SECRET";

    // Or your redirect URL for web based applications.
    String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
    String scope = "https://www.googleapis.com/auth/calendar";

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
        httpTransport, jsonFactory, clientId, clientSecret, Collections.singleton(scope));
    // Step 1: Authorize
    String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUrl).build();

    // Point or redirect your user to the authorizationUrl.
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Read the authorization code from the standard input stream.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String code = in.readLine();
    // End of Step 1

    // Step 2: Exchange
    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUrl)
        .execute();
    // End of Step 2

    Credential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets(clientId, clientSecret)
        .build().setFromTokenResponse(response);

    Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("YOUR_APPLICATION_NAME").build();
    ...
  }
...

Python

import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret can be found in Google Developers Console
FLOW = OAuth2WebServerFlow(
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    scope='https://www.googleapis.com/auth/calendar',
    user_agent='YOUR_APPLICATION_NAME/YOUR_APPLICATION_VERSION')

# To disable the local server feature, uncomment the following line:
# FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage('calendar.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)

# Build a service object for interacting with the API. Visit
# the Google Developers Console
# to get a developerKey for your own application.
service = build(serviceName='calendar', version='v3', http=http,
       developerKey='YOUR_DEVELOPER_KEY')

PHP


<?php
// If you've used composer to include the library, remove the following line
// and make sure to follow the standard composer autoloading.
// https://getcomposer.org/doc/01-basic-usage.md#autoloading
require_once 'google-api-php-client/autoload.php';

$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->addScope('https://www.googleapis.com/auth/calendar');

$service = new Google_Service_Calendar($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

...

.NET

using System;
using System.IO;
using System.Threading;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;

namespace Calendar.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            UserCredential credential;
            // This example uses the client_secrets.json file for authorization.
            // This file can be downloaded from the Google Developers Console
            // project.
            using (var stream = new FileStream("client_secrets.json", FileMode.Open,
                FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { CalendarService.Scope.Calendar },
                    "user", CancellationToken.None,
                    new FileDataStore("Calendar.Auth.Store")).Result;
            }

            // Create the service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Calendar API Sample",
            });

            ...
        }
    }
}

Ruby

The examples in this guide demonstrate command-line usage of the Ruby client library. To facilitate command-line development, the client library gem provide a utility called google-api. You can use this tool to generate a YAML file containing your authorization credentials. You can obtain a client ID and client secret from Google Developers Console.

google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client-id=CLIENT_ID --client-secret=CLIENT_SECRET

This command generates a .google-api.yaml file in your home directory. Copy this file to your working directory, or reference this location in your code. With the file in the appropriate location, use the following code to instantiate a client:

require 'rubygems'
require 'google/api_client'
require 'yaml'

oauth_yaml = YAML.load_file('.google-api.yaml')
client = Google::APIClient.new
client.authorization.client_id = oauth_yaml["client_id"]
client.authorization.client_secret = oauth_yaml["client_secret"]
client.authorization.scope = oauth_yaml["scope"]
client.authorization.refresh_token = oauth_yaml["refresh_token"]
client.authorization.access_token = oauth_yaml["access_token"]

if client.authorization.refresh_token && client.authorization.expired?
  client.authorization.fetch_access_token!
end

service = client.discovered_api('calendar', 'v3')