Google Picker

Google Picker API Developer's Guide

Conventional, platform-specific applications often provide File Open dialogs. But for countless web applications, the only choice presented to users is a plain input control. Users must cut-and-paste a URL, typically from another web browser tab or window.

Google Picker aims to change this by providing users a more modern experience:

  1. Familiar — The look-and-feel users will recognize from Google Drive and other Google properties.
  2. Graphical — A dialog experience, with many views showing previews or thumbnails.
  3. Streamlined — An inline, modal window, so users never leave the main application.

Web developers can incorporate Google Picker API by just adding a few lines of JavaScript.

Table of Contents

  1. Audience
  2. Application Requirements
  3. Register your project
  4. The "Hello World" Application
  5. Showing Different Views
  6. Handling Google Drive Items
  7. Rendering in Other Languages
  8. Supporting Older Browsers

Audience

This documentation is intended for developers who wish to add Google Picker API to their pages. A basic level of JavaScript fluency is required.

Read through this document to see code samples for common scenarios.

Consult the JSON Guide to understand the object format returned by the Google Picker API.

Refer to the Reference Guide for a complete API listing for the Google Picker API.

Application Requirements

Applications that use this interface must abide by all existing Terms of Service. Most importantly, you must correctly identify yourself in your requests.

Register your project

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 displayed list of APIs, make sure the Google Picker API status is set to ON.
  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 section.

Expand the OAuth 2.0 Client ID section to find your application's client ID and client secret or to set a redirect URI. Your application must send an OAuth 2.0 token when creating a Picker object with views that accesses private user data.

The "Hello World" Application

Create a Picker object using a PickerBuilder object. The Picker instance represents the Google Picker dialog, and is rendered on the page inside an IFRAME. Here's an example where a view with user's Photos is shown:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Picker Example</title>

    <script type="text/javascript">

      // The API developer key obtained from the Google Developers Console.
      var developerKey = 'ABC123 ... ';

      // The Client ID obtained from the Google Developers Console.
      var clientId = '123 ... .apps.googleusercontent.com';

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

      var pickerApiLoaded = false;
      var oauthToken;

      // Use the API Loader script to load google.picker and gapi.auth.
      function onApiLoad() {
        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 picking user Photos.
      function createPicker() {
        if (pickerApiLoaded && oauthToken) {
          var picker = new google.picker.PickerBuilder().
              addView(google.picker.ViewId.PHOTOS).
              setOAuthToken(oauthToken).
              setDeveloperKey(developerKey).
              setCallback(pickerCallback).
              build();
          picker.setVisible(true);
        }
      }

      // 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;
      }
    </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=onApiLoad"></script>
  </body>
</html>

Note: If you intend to support older browsers such as Microsoft Internet Explorer 6, modify the example slightly as shown in the Supporting Older Browsers section.

Let's walk through the relevant sections. First the Google API Loader script is loaded. It is instructed to load the Google Picker JavaScript and the Authentication API when its loading has completed. A callback is provided to create the Google Picker dialog once the Google Picker API script is loaded and the authentication is complete.

    <script type="text/javascript">
      function onApiLoad() {
        // Use the API Loader script to load the Authentication script.
        gapi.load('auth', {'callback': onAuthApiLoad});

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

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). Specifiy the view by type if you want additional control over how that view is rendered. If more than one view is added to the Picker, users switch from one view to another by clicking a tab on the left. Tabs can be logically grouped with ViewGroup objects.

In this simple application, a single view is specified by ID. A developer key should be obtained from Google Developers Console and passed to the PickerBuilder instance using the setDeveloperKey(developerKey) method. An OAuth 2.0 token is obtained using the Authentication API and passed to the PickerBuilder instance using the setOAuthToken(oauthToken) method. List of scopes needed to obtain the OAuth token for the corresponding Picker view is available here.

A method to call when the user selects an item (or cancels the dialog) is also specified. Once the Picker object is constructed, setVisible(true) is called so the user can see it.

    // Create and render a Picker object for picker user Photos.
    function createPicker() {
        var picker = new google.picker.PickerBuilder().
            addView(google.picker.ViewId.PHOTOS).
            setOAuthToken(oauthToken).
            setDeveloperKey(developerKey).
            setCallback(pickerCallback).
            build();
        picker.setVisible(true);
    }

The following code illustrates what you can do once the user selects Select or Cancel in the Google Picker dialog. The data object below is JSON-encoded. The google.picker.Response.ACTION field will always be set. 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. Find details about the data fields in the JSON Guide.

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

Showing Different Views

Specify a view by ViewId, or by an instance of a subclass of google.​picker.​View. Standard views offered by Google Picker API are the following:

View DescriptionViewId or Equivalent ClassOAuth Scope
All Google Drive items.google.picker.​ViewId.DOCS or google.picker.​DocsViewhttps://www.googleapis.com/auth/drive.readonly
Google Drive photos.google.picker.​ViewId.DOCS_IMAGEShttps://www.googleapis.com/auth/drive.readonly
Google Drive Documents.google.picker.​ViewId.DOCUMENTShttps://www.googleapis.com/auth/drive.readonly
Google Drive Presentations.google.picker.​ViewId.PRESENTATIONShttps://www.googleapis.com/auth/drive.readonly
Google Drive Spreadsheet.google.picker.​ViewId.SPREADSHEETShttps://www.googleapis.com/auth/drive.readonly
Google Drive Forms.google.picker.​ViewId.FORMShttps://www.googleapis.com/auth/drive.readonly
Google Drive photos and videos.google.picker.​ViewId.DOCS_IMAGES_AND_VIDEOShttps://www.googleapis.com/auth/drive.readonly
Google Drive videos.google.picker.​ViewId.DOCS_VIDEOShttps://www.googleapis.com/auth/drive.readonly
Google Drive Folders.google.picker.​ViewId.FOLDERShttps://www.googleapis.com/auth/drive.readonly
Adobe PDF files stored in Google Drive.google.picker.​ViewId.PDFShttps://www.googleapis.com/auth/drive.readonly
Upload documents to Google Drive.googlepicker.​DocsUploadViewhttps://www.googleapis.com/auth/drive
Picasa Web Albums photo albums.google.picker.​ViewId.PHOTO_ALBUMS or google.picker.​PhotoAlbumsViewhttps://www.googleapis.com/auth/photos
Picasa Web Albums photos.google.picker.​ViewId.PHOTOS or google.picker.​PhotosViewhttps://www.googleapis.com/auth/photos
Upload to Picasa Web Albums.google.picker.​ViewId.PHOTO_UPLOADhttps://www.googleapis.com/auth/photos.upload
Google Image Search.google.picker.​ViewId.IMAGE_SEARCH or google.picker.​ImageSearchView 
Google Maps.google.picker.​ViewId.MAPS or google.picker.​MapsView 
Video Search.google.picker.​ViewId.VIDEO_SEARCH or google.picker.​VideoSearchView 
Webcam photos and videos.google.picker.​ViewId.WEBCAM or google.picker.​WebCamViewhttps://www.googleapis.com/auth/photos.upload
Your YouTube videos.google.picker.​ViewId.YOUTUBEhttps://www.googleapis.com/auth/youtube
A collection of most recently selected items.google.picker.​ViewId.RECENTLY_PICKEDUse any of the above scopes.

The third column mentions the scope code that would be needed to obtain the OAuth 2.0 token for the view.

Use a class instance instead of the ViewId when you need type-specific control. For example, use the PhotosView to show Picasa Web Album's Featured Photos gallery.

    var picker = new google.picker.PickerBuilder().
        addView(new google.picker.PhotosView().
            setType(google.picker.PhotosView.Type.FEATURED)).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

For a comprehensive list of methods and classes, see the Reference Guide.

Ordinarily, the set of views provided to the PickerBuilder are listed vertically in a single line in the left of the Google Picker window. You may, however, prefer some of your views to be grouped visually under a common heading. Use view groups to achieve this effect. Note that the common heading must also be a view. For example, you can create a view group of photos views, headed by the Picasa Web Albums view, like the following:

    var picker = new google.picker.PickerBuilder().
        addViewGroup(
            new google.picker.ViewGroup(google.picker.ViewId.PHOTOS).
                addView(new google.picker.PhotosView().
                    setType(google.picker.PhotosView.Type.UPLOADED)).
                addView(new google.picker.PhotosView().
                    setType(google.picker.PhotosView.Type.FEATURED))).
        addView(google.picker.ViewId.RECENTLY_PICKED).
        setOAuthToken(oauthToken).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

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

    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();

Use PickerBuilder.​enableFeature() 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 Google video search picker demonstrating this feature:

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

Use View.​setQuery() to pre-populate search terms for views that include a web search. The following is a video search search example:

    picker = new google.picker.PickerBuilder().
        addView(new google.picker.View(google.picker.ViewId.VIDEO-SEARCH).
            setQuery('Hugging Cat')).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        build();

Handling Google Drive Items

The picker interface can display a list of the currently authenticated user's Google Drive files. When a user selects a file from the list, the file ID is returned, and the ID may be used by an app to access the file.

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:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Picker Example</title>

    <script type="text/javascript">

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

    // Use your own API developer key.
    var developerKey = 'AIzaSyBV6MeANy_ZaLB2f2c-XKCMA7hIu2Fy744';

    // Create and render a Picker object for searching images.
    function createPicker() {
      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(YOUR_APP_ID)
          .setOAuthToken(AUTH_TOKEN)
          .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 set here and the client ID used for authorizing access to a user's files must be contained in the same app. These values are shown in the Developers Console for a registered app.

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.

Rendering 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

Supporting Older Browsers

If you intend to support users using older browsers, follow these one-time steps:

  1. Download this file: https://www.google.com/ajax/picker/resources/rpc_relay.html.
  2. Place the file somewhere in the same domain as you application.
  3. Modify the Picker creation code, using the corrected path:
    var picker = new google.picker.PickerBuilder().
        addView(google.picker.ViewId.IMAGE_SEARCH).
        setDeveloperKey(developerKey).
        setCallback(pickerCallback).
        setRelayUrl('http://www.yoursite.com/somedir/rpc_relay.html').
        build();

Behind the scenes, the Google Picker API passes messages to your web page from a service hosted at Google. This is cross-domain communication, which is why special logic is necessary. On modern browsers, browser channels are used to relay the messages around. On older browsers, however, the security model requires us to bounce messages off of your server, in the same domain as your application.

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.