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 access token when creating a Picker object with views that accesses private user data. Use the Google Identity Services JavaScript SDK to request an access token.

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 code sample.

Load the Google Picker library and Google Identity Services SDK

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

    <script>
      let tokenClient;
      let accessToken = null;
      let pickerInited = false;
      let gisInited = false;

      // Use the API Loader script to load google.picker
      function onApiLoad() {
        gapi.load('picker', onPickerApiLoad);
      }

      function onPickerApiLoad() {
        pickerInited = true;
      }

      function gisLoaded() {
        // TODO(developer): Replace with your client ID and required scopes
        tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: 'YOUR_CLIENT_ID',
          scope: 'YOUR_SCOPES',
          callback: '', // defined later
        });
        gisInited = true;
    }
    </script>
    <!-- Load the Google API Loader script. -->
    <script async defer src="https://apis.google.com/js/api.js" onload="onApiLoad()"></script>
    <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
    

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

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 an instance of the Google Picker and displays it:

    // Create and render a Picker object for selecting from Google Drive
    function createPicker() {
      const showPicker = () => {
        // TODO(developer): Replace with your API key
        const picker = new google.picker.PickerBuilder()
            .addView(google.picker.ViewId.DOCS)
            .setOAuthToken(accessToken)
            .setDeveloperKey('YOUR_API_KEY')
            .setCallback(pickerCallback)
            .build();
        picker.setVisible(true);
      }

      // Use Google Identity Services to request an access token
      tokenClient.callback = async (response) => {
        if (response.error !== undefined) {
          throw (response);
        }
        accessToken = response.access_token;
        showPicker();
      };

      if (accessToken === null) {
        // Prompt the user to select a Google Account and ask for consent to share their data
        // when establishing a new session.
        tokenClient.requestAccessToken({prompt: 'consent'});
      } else {
        // Skip display of account chooser and consent dialog for an existing session.
        tokenClient.requestAccessToken({prompt: ''});
      }
    }
    

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) {
      let url = 'nothing';
      if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
        let doc = data[google.picker.Response.DOCUMENTS][0];
        url = doc[google.picker.Document.URL];
      }
      let message = `You picked: ${url}`;
      document.getElementById('result').innerText = 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.

    let 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:

     let 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:

    let 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