Google Apps Platform

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.
  3. In the sidebar on the left, select APIs & auth. In the displayed list of APIs, make sure the Google Calendar API status is set to ON.
  4. In the sidebar on the left, select Credentials.
  5. Find the lines labeled Client ID and Client secret. Note that there may be a client ID without a client secret, for use with Compute Engine and App Engine; in that case, create a new client ID and client secret by selecting Create New Client ID.

Java

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

import com.google.api.services.calendar.Calendar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

...

  public void setUp() throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    // 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";

    // Step 1: Authorize -->
    String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope)
        .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 -->
    AccessTokenResponse response = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory,
        clientId, clientSecret, code, redirectUrl).execute();
    // End of Step 2 <--

    GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
        response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
        response.refreshToken);

    Calendar service = new Calendar(httpTransport, accessProtectedResource, jsonFactory);
    service.setApplicationName("YOUR_APPLICATION_NAME");
    ...
  }
...

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

Edit the src/config.php file to put in your developer API information.

global $apiConfig;

$apiConfig = array(
    // Site name to show in Google's OAuth authentication screen
    'site_name' => 'www.example.org',

    // OAuth2 Setting, you can get these keys in Google Developers Console
    'oauth2_client_id' => 'YOUR_CLIENT_ID',
    'oauth2_client_secret' => 'YOUR_CLIENT_SECRET',
    'oauth2_redirect_uri' => 'YOUR_REDIRECT_URL',

    // The developer key; you get this from Google Developers Console
    'developer_key' => 'YOUR_DEVELOPER_KEY',
    ...

    // Which Authentication, Storage and HTTP IO classes to use.
    'authClass' => 'apiOAuth2',
    ....

    // Definition of service specific values like scopes, OAuth token URLs, etc
    'services' => array(
        'calendar' => array('scope' => 'https://www.googleapis.com/auth/calendar'),
    )
);

Invoke the Google Calendar API service and authenticate:

<?php
session_start();

require_once "../src/apiClient.php";
require_once "../src/contrib/apiCalendarService.php";

$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);

if (isset($_SESSION['oauth_access_token'])) {
  $apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
  $token = $apiClient->authenticate();
  $_SESSION['oauth_access_token'] = $token;
}
...

.NET

using System;
using System.Threading;
using System.Threading.Tasks;

using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;

namespace Calendar.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = "CLIENT_ID_HERE",
                    ClientSecret = "CLIENT_SECRET_HERE",
                },
                new[] { CalendarService.Scope.Calendar },
                "user",
                CancellationToken.None).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')

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.