The Google Picker API

The Google picker is a "File Open" dialog for the information stored on Google Drive. The Google picker has these features:

  • A similar look-and-feel to the Google Drive UI.
  • Several views showing previews and thumbnails of Drive files.
  • An inline, modal window, so users never leave the main application.
The Google Picker API is a JavaScript API you can use in your Web apps to enable users to open or upload Google Drive files.

Application requirements

Applications using the Google picker must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests.

Enable the Google Picker API

To get started using Google Picker API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

If you haven't done so already, create your application's API key by clicking Create credentials > API key. Next, look for your API key in the API keys section.

If you haven't done so already, create your OAuth 2.0 credentials by clicking Create credentials > OAuth client ID. After you've created the credentials, you can see your client ID on the Credentials page. Click the client ID for details, such as client secret, redirect URIs, JavaScript origins address, and email address. Your application must send an OAuth 2.0 token when creating a Picker object with views that accesses private user data.

Display the Google picker

The remainder of this guide covers how to load and display the Google picker from a Web app. To view the complete example, navigate to the Google Picker example.

Load the Google Picker library

To load the Google Picker library, call gapi.load() with the library name and a callback function to invoke after a successful load:

      // Use the API Loader script to load google.picker and gapi.auth.
      function onApiLoad() {
        gapi.load('auth2', onAuthApiLoad);
        gapi.load('picker', onPickerApiLoad);
      }
    </script>
    <!-- Load the Google API Loader script. -->
    <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>

The onApiLoad() function loads the authentication and Google Picker libraries. The onPickerApiLoad() callback function is called after the Google Picker library successfully loads.

Implement the successful load callback function

The onPickerApiLoad() callback function sets a flag to indicate that the Picker library has successfully loaded. Then onPickerApiLoad calls the createPicker function to create and display the Google Picker:

    function onPickerApiLoad() {
        pickerApiLoaded = true;
        createPicker();
      }

Display the Google Picker

The createPicker() function checks to ensure the Google Picker API finished loading and that an oauthToken is created. Then, this function creates a new instance of the Google Picker and displays it:

// Create and render a Picker object for selecting from Google Drive
    function createPicker() {
        if (pickerApiLoaded && oauthToken) {
          var picker = new google.picker.PickerBuilder().
              addView(google.picker.ViewId.DOCS).
              setOAuthToken(oauthToken).
              setDeveloperKey(developerKey).
              setCallback(pickerCallback).
              build();
          picker.setVisible(true);
        }
      }
    }

To create a Picker instance, you must provide a View, an oauthToken, a developerKey, and a callback function to call upon success (pickerCallback).

A Picker renders one view at a time. Specify at least one view, either by ID (google.​picker.​ViewId.*) or by creating an instance of a type (google.​picker.​*View). Specify the view by type for additional control over how that view is rendered.

If more than one view is added to the Google Picker, users switch from one view to another by clicking a tab on the left. Tabs can be logically grouped with ViewGroup objects.

Implement the Picker callback

A Picker callback can be used to react to user interactions in the Google Picker, such as selecting a file or pressing Cancel.

    // A simple callback implementation.
    function pickerCallback(data) {
        var url = 'nothing';
        if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
          var doc = data[google.picker.Response.DOCUMENTS][0];
          url = doc[google.picker.Document.URL];
        }
        var message = 'You picked: ' + url;
        document.getElementById('result').innerHTML = message;
      }

The callback receives a JSON-encoded data object. This object contains any actions the user performs with the Google Picker (google.picker.Response.ACTION). If the user selects an item, the google.picker.Response.DOCUMENTS array is also populated. In this example the google.picker.Document.URL is shown on the main page. For details about the data fields, refer to the JSON Guide.

Filter specific file types

Use view groups as a way of filtering out specific items. In the following example, the "Google Drive" sub-view shows only documents and presentations.

var picker = new google.picker.PickerBuilder().
        addViewGroup(
            new google.picker.ViewGroup(google.picker.ViewId.DOCS).
                addView(google.picker.ViewId.DOCUMENTS).
                addView(google.picker.ViewId.PRESENTATIONS)).
        setOAuthToken(oauthToken).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

Tune the Google Picker's appearance

Use the PickerBuilder.enableFeature() function to fine-tune the appearance of the Google Picker window. For instance, if you only have a single view, you may want to hide the navigation pane to give users more space to see items. Here's an example of a spreadsheets search picker demonstrating this feature:

var picker = new google.picker.PickerBuilder().
        addView(google.picker.ViewId.SPREADSHEETS).
        enableFeature(google.picker.Feature.NAV_HIDDEN).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

Render the Google picker in other languages

Specify the UI language by providing the locale to the PickerBuilder instance using the setLocale(locale) method. The following is a French example:

    var picker = new google.picker.PickerBuilder().
        addView(google.picker.ViewId.IMAGE_SEARCH).
        setLocale('fr').
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

The following is the list of locales currently supported:

af
am
ar
bg
bn
ca
cs
da
de
el
en
en-GB
es
es-419
et
eu
fa
fi
fil
fr
fr-CA
gl
gu
hi
hr
hu
id
is
it
iw
ja
kn
ko
lt
lv
ml
mr
ms
nl
no
pl
pt-BR
pt-PT
ro
ru
sk
sl
sr
sv
sw
ta
te
th
tr
uk
ur
vi
zh-CN
zh-HK
zh-TW
zu

Google Picker example

Following is the entire Google Picker example:

The following picker example illustrates an image selector/uploader page that could be opened from an Open or Upload Drive files button in a web app. This example demonstrates how to set the AppId value, and incorporates some useful picker features such as enabling multi-select, hiding the navigation pane, and choosing the user account with the app's current OAuth 2.0 token:

drive/picker/helloworld.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>Google Picker Example</title>

    <script type="text/javascript">

    // The Browser API key obtained from the Google API Console.
    // Replace with your own Browser API key, or your own key.
    var developerKey = 'xxxxxxxYYYYYYYY-12345678';

    // The Client ID obtained from the Google API Console. Replace with your own Client ID.
    var clientId = "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com"

    // Replace with your own project number from console.developers.google.com.
    // See "Project number" under "IAM & Admin" > "Settings"
    var appId = "1234567890";

    // Scope to use to access user's Drive items.
    var scope = ['https://www.googleapis.com/auth/drive.file'];

    var pickerApiLoaded = false;
    var oauthToken;

    // Use the Google API Loader script to load the google.picker script.
    function loadPicker() {
      gapi.load('auth', {'callback': onAuthApiLoad});
      gapi.load('picker', {'callback': onPickerApiLoad});
    }

    function onAuthApiLoad() {
      window.gapi.auth.authorize(
          {
            'client_id': clientId,
            'scope': scope,
            'immediate': false
          },
          handleAuthResult);
    }

    function onPickerApiLoad() {
      pickerApiLoaded = true;
      createPicker();
    }

    function handleAuthResult(authResult) {
      if (authResult && !authResult.error) {
        oauthToken = authResult.access_token;
        createPicker();
      }
    }

    // Create and render a Picker object for searching images.
    function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes("image/png,image/jpeg,image/jpg");
        var picker = new google.picker.PickerBuilder()
            .enableFeature(google.picker.Feature.NAV_HIDDEN)
            .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
            .setAppId(appId)
            .setOAuthToken(oauthToken)
            .addView(view)
            .addView(new google.picker.DocsUploadView())
            .setDeveloperKey(developerKey)
            .setCallback(pickerCallback)
            .build();
         picker.setVisible(true);
      }
    }

    // A simple callback implementation.
    function pickerCallback(data) {
      if (data.action == google.picker.Action.PICKED) {
        var fileId = data.docs[0].id;
        alert('The user selected: ' + fileId);
      }
    }
    </script>
  </head>
  <body>
    <div id="result"></div>

    <!-- The Google API Loader script. -->
    <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
  </body>
</html>

The AppId and the client ID, used for authorizing access to a user's files, must be contained in the same app. Within the API Console, AppId can be identified as the "Project number" on the "IAM & Admin" > "Settings" page, in the developer console.

Important:The setOAuthToken function allows an app to use the current auth token to determine which Google account the picker uses to display the files. If a user is signed into multiple Google accounts, this allows the picker to display the files of the appropriate authorized account.

After obtaining the file ID from the picker when opening files, an application can then fetch the file metadata and download the file content as described in the reference documentation for files.get.