Click here to see your recently viewed pages and most viewed pages.
Hide
Drive REST API

Files: get

Gets a file's metadata by ID. Try it now or see an example.

Request

HTTP request

GET https://www.googleapis.com/drive/v2/files/fileId

Parameters

Parameter name Value Description
Path parameters
fileId string The ID for the file in question.
Optional query parameters
acknowledgeAbuse boolean Whether the user is acknowledging the risk of downloading known malware or other abusive files. (Default: false)
projection string This parameter is deprecated and has no function.

Acceptable values are:
  • "BASIC": Deprecated
  • "FULL": Deprecated
revisionId string Specifies the Revision ID that should be downloaded. Ignored unless alt=media is specified.
updateViewedDate boolean Whether to update the view date after successfully retrieving the file. (Default: false)

Request body

Do not supply a request body with this method.

Response

By default, this responds with a Files resource in the response body. If you provide the URL parameter alt=media, then it will respond with the file contents in the response body. Downloading content with alt=media only works if the content is stored in Drive, so it does not work for shortcuts. Also, it currently does not support exporting Google Docs; use exportLinks from the Files resource instead. See also Download Files.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library.

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
import java.io.InputStream;

// ...

public class MyClass {

  // ...

  /**
   * Print a file's metadata.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to print metadata for.
   */
  private static void printFile(Drive service, String fileId) {

    try {
      File file = service.files().get(fileId).execute();

      System.out.println("Title: " + file.getTitle());
      System.out.println("Description: " + file.getDescription());
      System.out.println("MIME type: " + file.getMimeType());
    } catch (IOException e) {
      System.out.println("An error occured: " + e);
    }
  }

  /**
   * Download a file's content.
   *
   * @param service Drive API service instance.
   * @param file Drive File instance.
   * @return InputStream containing the file's content if successful,
   *         {@code null} otherwise.
   */
  private static InputStream downloadFile(Drive service, File file) {
    if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
      try {
        HttpResponse resp =
            service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
                .execute();
        return resp.getContent();
      } catch (IOException e) {
        // An error occurred.
        e.printStackTrace();
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }

  // ...
}

.NET

Uses the .NET client library.

using Google.Apis.Authentication;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Print a file's metadata.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to print metadata for.</param>
  public static void printFile(DriveService service, String fileId) {
    try {
      File file = service.Files.Get(fileId).Execute();

      Console.WriteLine("Title: " + file.Title);
      Console.WriteLine("Description: " + file.Description);
      Console.WriteLine("MIME type: " + file.MimeType);
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
  }

  /// <summary>
  /// Download a file and return a string with its content.
  /// </summary>
  /// <param name="authenticator">
  /// Authenticator responsible for creating authorized web requests.
  /// </param>
  /// <param name="file">Drive File instance.</param>
  /// <returns>File's content if successful, null otherwise.</returns>
  public static System.IO.Stream DownloadFile(
      IAuthenticator authenticator, File file) {
    if (!String.IsNullOrEmpty(file.DownloadUrl)) {
      try {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
            new Uri(file.DownloadUrl));
        authenticator.ApplyAuthenticationToRequest(request);
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        if (response.StatusCode == HttpStatusCode.OK) {
          return response.GetResponseStream();
        } else {
          Console.WriteLine(
              "An error occurred: " + response.StatusDescription);
          return null;
        }
      } catch (Exception e) {
        Console.WriteLine("An error occurred: " + e.Message);
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }
  }

  //...

}

PHP

Uses the PHP client library.

/**
 * Print a file's metadata.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param string $fileId ID of the file to print metadata for.
 */
function printFile($service, $fileId) {
  try {
    $file = $service->files->get($fileId);

    print "Title: " . $file->getTitle();
    print "Description: " . $file->getDescription();
    print "MIME type: " . $file->getMimeType();
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}

/**
 * Download a file's content.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param File $file Drive File instance.
 * @return String The file's content if successful, null otherwise.
 */
function downloadFile($service, $file) {
  $downloadUrl = $file->getDownloadUrl();
  if ($downloadUrl) {
    $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
    if ($httpRequest->getResponseHttpCode() == 200) {
      return $httpRequest->getResponseBody();
    } else {
      // An error occurred.
      return null;
    }
  } else {
    // The file doesn't have any content stored on Drive.
    return null;
  }
}

Python

Uses the Python client library.

from apiclient import errors
from apiclient import http
# ...

def print_file_metadata(service, file_id):
  """Print a file's metadata.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to print metadata for.
  """
  try:
    file = service.files().get(fileId=file_id).execute()

    print 'Title: %s' % file['title']
    print 'MIME type: %s' % file['mimeType']
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def print_file_content(service, file_id):
  """Print a file's content.

  Args:
    service: Drive API service instance.
    file_id: ID of the file.

  Returns:
    File's content if successful, None otherwise.
  """
  try:
    print service.files().get_media(fileId=file_id).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def download_file(service, file_id, local_fd):
  """Download a Drive file's content to the local filesystem.

  Args:
    service: Drive API Service instance.
    file_id: ID of the Drive file that will downloaded.
    local_fd: io.Base or file object, the stream that the Drive file's
        contents will be written to.
  """
  request = service.files().get_media(fileId=file_id)
  media_request = http.MediaIoBaseDownload(local_fd, request)

  while True:
    try:
      download_progress, done = media_request.next_chunk()
    except errors.HttpError, error:
      print 'An error occurred: %s' % error
      return
    if download_progress:
      print 'Download Progress: %d%%' % int(download_progress.progress() * 100)
    if done:
      print 'Download Complete'
      return

Ruby

Uses the Ruby client library.

##
# Print a file's metadata.
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of file to print
# @return nil
def print_file(client, file_id)
  drive = client.discovered_api('drive', 'v2')
  result = client.execute(
    :api_method => @drive.files.get,
    :parameters => { 'fileId' => file_id })
  if result.status == 200
    file = result.data
    puts "Title: #{file.title}"
    puts "Description: #{file.description}"
    puts "MIME type: #{file.mime_type}"
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

##
# Download a file's content
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [Google::APIClient::Schema::Drive::V2::File]
#   Drive File instance
# @return
#   File's content if successful, nil otherwise
def download_file(client, file)
  if file.download_url
    result = client.execute(:uri => file.download_url)
    if result.status == 200
      return result.body
    else
      puts "An error occurred: #{result.data['error']['message']}"
      return nil
    end
  else
    # The file doesn't have any content stored on Drive.
    return nil
  end
end

JavaScript

Uses the JavaScript client library.

/**
 * Print a file's metadata.
 *
 * @param {String} fileId ID of the file to print metadata for.
 */
function printFile(fileId) {
  var request = gapi.client.drive.files.get({
    'fileId': fileId
  });
  request.execute(function(resp) {
    console.log('Title: ' + resp.title);
    console.log('Description: ' + resp.description);
    console.log('MIME type: ' + resp.mimeType);
  });
}

/**
 * Download a file's content.
 *
 * @param {File} file Drive File instance.
 * @param {Function} callback Function to call when the request is complete.
 */
function downloadFile(file, callback) {
  if (file.downloadUrl) {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.downloadUrl);
    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}

Go

Uses the Go client library.

import (
  "code.google.com/p/google-api-go-client/drive/v2"
  "fmt"
  "net/http"
  "io/ioutil"
)

// PrintFile fetches and displays the given file.
func PrintFile(d *drive.Service, fileId string) error {
  f, err := d.Files.Get(fileId).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return err
  }
  fmt.Printf("Title: %v", f.Title)
  fmt.Printf("Description: %v", f.Description)
  fmt.Printf("MIME type: %v", f.MimeType)
  return nil
}


// DownloadFile downloads the content of a given file object
func DownloadFile(d *drive.Service, t http.RoundTripper, f *drive.File) (string, error) {
  // t parameter should use an oauth.Transport
  downloadUrl := f.DownloadUrl
  if downloadUrl == "" {
    // If there is no downloadUrl, there is no body
    fmt.Printf("An error occurred: File is not downloadable")
    return "", nil
  }
  req, err := http.NewRequest("GET", downloadUrl, nil)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  resp, err := t.RoundTrip(req)
  // Make sure we close the Body later
  defer resp.Body.Close()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  body, err := ioutil.ReadAll(resp.Body)
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return "", err
  }
  return string(body), nil
}

Objective-C

Uses the Objective-C client library.

#import "GTLDrive.h"
// ...

+ (void)printFileMetadataWithService:(GTLServiceDrive *)service
                              fileId:(NSString *)fileId {
  GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:fileId];

  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *file,
                            NSError *error) {
        if (error == nil) {
          NSLog(@"Title: %@", file.title);
          NSLog(@"Description: %@", file.descriptionProperty);
          NSLog(@"MIME type: %@", file.mimeType);
        } else {
          NSLog(@"An error occurred: %@", error);
        }
      }];
}

+ (void)downloadFileContentWithService:(GTLServiceDrive *)service
                                  file:(GTLDriveFile *)file
                       completionBlock:(void (^)(NSData *, NSError *))completionBlock {
  if (file.downloadUrl != nil) {
    // More information about GTMHTTPFetcher can be found on
    // <a href="http://code.google.com/p/gtm-http-fetcher">http://code.google.com/p/gtm-http-fetcher</a>
    GTMHTTPFetcher *fetcher =
      [service.fetcherService fetcherWithURLString:file.downloadUrl];

    [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) {
      if (error == nil) {
        // Success.
        completionBlock(data, nil);
      } else {
        NSLog(@"An error occurred: %@", error);
        completionBlock(nil, error);
      }
    }];
  } else {
    completionBlock(nil,
                    [NSError errorWithDomain:NSURLErrorDomain
                                        code:NSURLErrorBadUrl
                                    userInfo:nil]);
  }
}

// ...

Try it!

Use the APIs Explorer below to call this method on live data and see the response.