Google Drive SDK

Use Application-Owned Accounts

You may want to use Google Drive to store files on behalf of your application and not on a user’s Drive. For example, you could store files in an application-owned account and simply share them with your users, keeping ownership and control over the files. Or, you might just want to store files and make sure they are always accessible publicly. Basically, in these kinds of cases you want to be able to create and keep full control over application-owned files in a Google Drive. In such cases you can use application-owned accounts.

There are two types of accounts that can be owned by your application. Service accounts or regular Google accounts.

Because it is not possible to access the Google Drive web user interface of a service account, it is not possible to purchase additional Google Drive storage for this type of accounts. For that reason you may prefer using a regular account instead of a service account.

Use regular Google accounts as application-owned accounts

You may create a regular Google account like any user would, by going through the Google account sign-up flow or by creating an account on your Google Apps domain. Make sure it is then never used by an actual person but only by your application.

To be able to access the account’s Drive programmatically you need to manually go through the OAuth 2.0 web-server flow once and then store or hard-code the user’s credentials, such as the refresh token, to be able to programmatically access its Drive. For more information about the web server flow for Drive, see Implementing Server-side Authorization.

Use service accounts as application-owned accounts

Service accounts are accounts associated with a service or a project. They do not belong to a user and can only be accessed programmatically by the associated application.

Just like regular user accounts, service accounts have access to Google Drive through the Google Drive API. This allows you to authenticate as the service account in order to manage a Drive that belongs to your project.

There are currently two types of service accounts offered by Google. Jump to the section covering the type of service account you plan to use:

Google Developers Console project service accounts

Service accounts can be created in the Google Developers Console. They are tied to your Developers Console project. These service accounts are typically named <some-id>@developer.gserviceaccount.com

Create the service account and its credentials

First you need a working Developers Console project with the Google Drive API enabled.

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Drive API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To set up a service account, select Create New Client ID. Specify that your application type is service account, and then select Create Client ID. A dialog box appears; to proceed, select Okay, got it. (If you already have a service account, you can add a new key by selecting Generate new key beneath the existing service-account credentials. A dialog box appears; to proceed, select Okay, got it.)

After downloading the file and closing the dialog, you will be able to get the Service Account's email address.

You should now have gathered the Private Key file and your Service Account's email address. You are ready to instantiate an authorized Drive service Object.

Instantiate a Drive service object

This section shows how to instantiate a service object and then authorize it to make API requests using OAuth 2.0 Service Accounts credentials. You should now have the Service Account's private key file - in a PKCS #12 format - and the email of the Service Account.

Java

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
...

/** Email of the Service Account */
private static final String SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";

/** Path to the Service Account's Private Key file */
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/path/to/<public_key_fingerprint>-privatekey.p12";

/**
 * Build and returns a Drive service object authorized with the service accounts.
 *
 * @return Drive service object that is ready to make requests.
 */
public static Drive getDriveService() throws GeneralSecurityException,
    IOException, URISyntaxException {
  HttpTransport httpTransport = new NetHttpTransport();
  JacksonFactory jsonFactory = new JacksonFactory();
  GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
      .setServiceAccountScopes(DriveScopes.DRIVE)
      .setServiceAccountPrivateKeyFromP12File(
          new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
      .build();
  Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
      .setHttpRequestInitializer(credential).build();
  return service;
}

Python

import httplib2
import pprint
import sys

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Email of the Service Account.
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file.
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def createDriveService():
  """Builds and returns a Drive service object authorized with the given service account.

  Returns:
    Drive service object.
  """
  f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
  key = f.read()
  f.close()

  credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope='https://www.googleapis.com/auth/drive')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('drive', 'v2', http=http)

PHP

<?php

require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();

$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12';

/**
 * Build and returns a Drive service object authorized with the service accounts.
 *
 * @return Google_DriveService service object.
 */
function buildService() {
  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      SERVICE_ACCOUNT_EMAIL,
      array(DRIVE_SCOPE),
      $key);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}

?>

.NET

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Drive.v2;
using Google.Apis.Util;

public class MyClass {

  private const string SERVICE_ACCOUNT_EMAIL = "<some-id>@developer.gserviceaccount.com";
  private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"\path\to\<public_key_fingerprint>-privatekey.p12";

  /// <summary>
  /// Build a Drive service object authorized with the service account.
  /// </summary>
  /// <returns>Drive service object.</returns>
  static DriveService BuildService() {
    X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
        X509KeyStorageFlags.Exportable);

    var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
    {
      ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
      Scope = DriveService.Scopes.Drive.GetStringValue(),
    };
    var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

    return new DriveService(auth);
  }
}

Ruby

require 'google/api_client'

## Email of the Service Account #
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

## Path to the Service Account's Private Key file #
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

##
# Build a Drive client instance authorized with the service account.
#
# @return [Google::APIClient]
#   Client instance
def build_client()
    key = Google::APIClient::PKCS12.load_key(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'notasecret')
    asserter = Google::APIClient::JWTAsserter.new(SERVICE_ACCOUNT_EMAIL,
        'https://www.googleapis.com/auth/drive', key)
    client = Google::APIClient.new
    client.authorization = asserter.authorize()
    client
end

JavaScript

For security reasons service accounts are not supported in client-side
Javascript. Service accounts for server-side Javascript is not yet
supported.

Now that you are authorized and have instantiated a Drive service, have a look at the next steps.

Google App Engine project service accounts

Each App Engine project has an associated service account. This type of service accounts is typically named <application-id>@appspot.gserviceaccount.com. Its name can be found in your Application Settings page in your App Engine application's Administration Console under Service Account Name.

Where to find the Service Account's email

Create a Developers Console project and enable the Drive API

First you need a working Developers Console project with the Google Drive API enabled.

If you haven't already registered your application with the Google Developers Console, then set up a project and application in the Developers Console. The system guides you through the process of choosing or creating a project and registering a new application, and it automatically activates the API for you.

If you've already registered your application with the Developers Console, then follow this procedure instead:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the Drive API.
  4. In the sidebar on the left, select Credentials.

In either case, you end up on the application's credentials page.

To find your application's API key, expand the Browser Key or Server Key sections.

Instantiate a Drive service object

This section shows how to instantiate a Drive service object and then authorize it to make API requests using OAuth 2.0 Service Accounts credentials in an App Engine environment. You should now have the API Key of your project.

Java

import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
...

/** The API Key of the project */
private static final String API_KEY = "the_api_key_of_the_project";

/**
 * Build and returns a Drive service object authorized with the
 * application's service accounts.
 *
 * @return Drive service object that is ready to make requests.
 */
public static Drive getDriveService() throws GeneralSecurityException,
    IOException, URISyntaxException {
  HttpTransport httpTransport = new NetHttpTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  AppIdentityCredential credential =
      new AppIdentityCredential.Builder(DriveScopes.DRIVE).build();
  GoogleClientRequestInitializer keyInitializer =
      new CommonGoogleClientRequestInitializer(API_KEY);
  Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
      .setHttpRequestInitializer(credential)
      .setGoogleClientRequestInitializer(keyInitializer)
      .build();
  return service;
}

Python

import httplib2
import pprint
import sys

from apiclient.discovery import build
from oauth2client.appengine import AppAssertionCredentials

# The API Key of the project.
API_KEY = 'the_api_key_of_the_project'

def createDriveService():
  """Builds and returns a Drive service object authorized with the
  application's service account.

  Returns:
    Drive service object.
  """
  credentials = AppAssertionCredentials(
      scope='https://www.googleapis.com/auth/drive')
  http = httplib2.Http()
  http = credentials.authorize(http)

  return build('drive', 'v2', http=http, developerKey=API_KEY)

Next steps

Once you are comfortable authorizing Drive API requests, you're ready to upload files and perform any of the other operations described in "Manage Drive Files." You can learn more about available API methods in the API Reference, and you can review our end-to-end Example Apps to examine some working code.

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.