Google Drive Web APIs

Open Files

The Google Drive UI provides two ways to open files:

  • The Open with contextual menu item
  • The Google Picker dialog for opening files

To see what these UI features look like, check the overview of What Can You Do with the Drive platform?. The rest of this page describes how to integrate your app with these Drive UI features to open files stored in Google Drive.

Open files using the Open with contextual menu

When a user chooses files in Google Drive and selects the Open with menu option, Drive redirects the user to the Open URL for the selected application (this URL is defined when you enable the Drive platform). The redirected request from the user's browser contains this important information in the state parameter:

  • The ID of the file(s) to open.
  • The action, set to open.
  • The userId of the authenticated user.

You'll need the file ID to fetch file metadata and download file content. The state parameter is URL-encoded, so you'll need to handle the escape characters and parse it as JSON. In JSON notation, state information for an Open with URL looks like the following:

  "ids": ["0Bz0bd"],

The following example illustrates how to load state information using the supported client libraries.


     * An object representing the state parameter passed into this application
     * from the Drive UI integration (i.e. Open With or Create New). Required
     * for Gson to deserialize the JSON into POJO form.
    public class State {
       * Action intended by the state.
      public String action;

       * IDs of files on which to take action.
      public Collection<String> ids;

       * Parent ID related to the given action.
      public String parentId;

       * Empty constructor required by Gson.
      public State() {}

       * Create a new State given its JSON representation.
       * @param json Serialized representation of a State.

      public State(String json) {
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        State other = gson.fromJson(json, State.class);
        this.action = other.action;
        this.ids = other.ids;
        this.parentId = other.parentId;


    class DriveState(object):
      """Store state provided by Drive."""

      def __init__(self, state):
        """Create a new instance of drive state.

        Parse and load the JSON state parameter.

          state: State query parameter as a string.
        state_data = json.loads(state)
        self.action = state_data['action']
        self.ids = map(str, state_data.get('ids', []))


     * Check to see if the 'state' parameter exists, with
     * the mode and specified file IDs (on open) or a folder parentId
     * (on create).
       * State should always be defined
      if (isset($_GET['state'])) {
        $state = json_decode(stripslashes($_GET['state']));
        $_SESSION['mode'] = $state->action;

        if (isset($state->ids)){
          $_SESSION['fileIds'] = $state->ids;
        } else {
          $_SESSION['fileIds'] = array();
        if (isset($state->parentId)) {
          $_SESSION['parentId'] = $state->parentId;
        } else {
          $_SESSION['parentId'] = null;
      } else {
        $error = 'Code defined, but no state.  Condition shouldn\'t exist.';
        throw new Exception($error);


    public ActionResult Index(string state, string code)

        DriveState driveState = new DriveState();

        if (!string.IsNullOrEmpty(state))
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            driveState = jsonSerializer.Deserialize<DriveState>(state);

        if (driveState.action == "open")
            return OpenWith(driveState);
            return CreateNew(driveState);

    public class DriveState
        public string action { get; set; }
        public string parentId { get; set; }
        public string[] ids { get; set; }


# Parse the state as JSON if present
s = params[:state] || '{}'
state = MultiJson.decode(s)

# Check action...
if state['action'] == 'create'
  # Create a new file
  parent_id = state['parentId']
  # Open one or more files
  file_ids = state['ids']

Once it has the file ID and an access token, an app can check permissions, fetch the file metadata, and download the file content as described in the reference documentation for files.get.

Open and convert Google Docs in your app

An app registered with the Import option enabled in the Drive SDK options in the Developers Console can import supported Google Doc formats. This means that if a user selects Open with for a Google doc, the app can convert it to a format that the app can handle. When Open with triggers a conversion this way, Drive evaluates the MIME types an app can open (set during registration) and extrapolates the list of formats that the app can import.

Google Doc formats and supported export MIME types map to each other as follows:

Google Doc Format Conversion Format Corresponding MIME type
Documents HTML text/html
Plain text text/plain
Rich text application/rtf
Open Office doc application/vnd.oasis.opendocument.text
PDF application/pdf
MS Word document application/vnd.openxmlformats-officedocument.wordprocessingml.document
Spreadsheets MS Excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Open Office sheet application/x-vnd.oasis.opendocument.spreadsheet
PDF application/pdf
Drawings JPEG image/jpeg
PNG image/png
SVG image/svg+xml
PDF application/pdf
Presentations MS PowerPoint application/vnd.openxmlformats-officedocument.presentationml.presentation
Open Office, PDF application/pdf

When a user selects an app from the Open with contextual menu for a Google Doc, Drive redirects the user to the Open URL for the selected application. The redirected request from the user's browser contains this important information in the state parameter:

  • The action, set to open.
  • The exportIds to use.

Once it has the export IDs, an app can fetch the file metadata and extract the desired download URL from the exportLinks values. These are key-value pairs in which the key is a MIME type and the value is the download URL for the converted file. The app can download the converted file content from the download URL. Apps can display converted files as read-only, or let users save them as new files.

Open and upload files using the Google Picker API

If you want to let users open or upload Google Drive files directly from your web app independently of the Drive UI, you can use the Google Picker API. The picker can display a list of the currently authenticated user's Drive files in an interface like the following:

Select a file from a picker window.

When a user selects a file from the list, the file ID is returned, and the ID may be used by your app to access the file. You can also add to a picker dialog the capability to upload files to Google Drive.

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">
    <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);
      var picker = new google.picker.PickerBuilder()
          .addView(new google.picker.DocsUploadView())

    // 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);
    <div id="result"></div>

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

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.