The Google Picker API

Stay organized with collections Save and categorize content based on your preferences.

Google Picker dialog.

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 let users to open or upload 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.

You must also have a Google Cloud project.

Set up your environment

To get started using Google Picker API, you must set up your environment.

Enable the API

Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.

  • In the Google Cloud console, enable the Google Picker API.

    Enable the API

Create an API key

An API key is a long string containing upper and lower case letters, numbers, underscores, and hyphens, such as AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe. This authentication method is used to anonymously access publicly available data, such as Google Workspace files shared using the "Anyone on the Internet with this link" sharing setting. For more details, see Authenticate using API keys.

To create an API key:

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create credentials > API key.
  3. Your new API key is displayed.
    • Click Copy to copy your API key for use in your app's code. The API key can also be found in the "API keys" section of your project's credentials.
    • Click Restrict key to update advanced settings and limit use of your API key. For more details, see Applying API key restrictions.

Authorize credentials for a web application

To authenticate as an end user and access user data in your app, you need to create one or more OAuth 2.0 Client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, you must create a separate client ID for each platform.

  1. In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  2. Click Create Credentials > OAuth client ID.
  3. Click Application type > Web application.
  4. In the Name field, type a name for the credential. This name is only shown in the Google Cloud console.
  5. Add authorized URIs related to your app:
    • Client-side apps (JavaScript)–Under Authorized JavaScript origins, click Add URI. Then, enter a URI to use for browser requests. This identifies the domains from which your application can send API requests to the OAuth 2.0 server.
    • Server-side apps (Java, Python, and more)–Under Authorized redirect URIs, click Add URI. Then, enter an endpoint URI to which the OAuth 2.0 server can send responses.
  6. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.

    Note the Client ID. Client secrets aren't used for Web applications.

  7. Click OK. The newly created credential appears under OAuth 2.0 Client IDs.
Important: Your application must send an OAuth 2.0 access token with views that access private user data when creating a Picker object. To request an access token, see Using OAuth 2.0 to Access Google APIs.

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

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 finishes loading and that an OAuth token is created. Then, this function creates an instance of the Google Picker and displays it:

    // Create and render a Google Picker object for selecting from 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);
      }

      // 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 Google Picker instance, you must provide a View, an oauthToken, a developerKey, and a callback function to call upon success (pickerCallback).

A Picker object renders one View at a time. Specify at least one view, either by ViewId (google.​picker.​ViewId.*) or by creating an instance of a type (google.​picker.​*View). Specify the view by type for additional control over how the 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 Reference.

Filter specific file types

Use a ViewGroup as a way of filtering out specific items. In the following example, the "Google Drive" subview 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 language 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