Google Drive SDK

Files: get

Gets a file's metadata by ID. To download a file's content, send an authorized HTTP GET request to the file's downloadUrl. See an example.

Request

HTTP Request

GET https://www.googleapis.com/drive/v1/files/id

Parameters

Parameter Name Value Description
Required Parameters
id string The ID for this file.
Optional Parameters
projection string Restrict information returned for simplicity and optimization.

Acceptable values are:
  • "BASIC" - Includes only the basic metadata fields (as of Drive API v1, this includes all fields).
  • "FULL" - Includes all metadata fields.
updateViewedDate boolean Whether to update the view date after successfully retrieving the file. Default value is false.

Request Body

Do not supply a request body with this method.

Response

If successful, this method returns a Files resource in the response body.

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.v1;
using Google.Apis.Drive.v1.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).Fetch();

            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 = authenticator.CreateHttpWebRequest(
                    "GET", new Uri(file.DownloadUrl));
                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 apiDriveService $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 apiDriveService $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 apiHttpRequest($downloadUrl, 'GET', null, null);
    $httpRequest = $service->getIo()->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
# ...

def print_file(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(id=file_id).execute()

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


def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp
      return None
  else:
    # The file doesn't have any content stored on Drive.
    return None

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)
  result = client.execute(
    :api_method => @drive.files.get,
    :parameters => { 'id' => file_id })
  if result.status == 200
    file = result.data
    puts "Title: #{file.data}"
    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::V1::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
  else
    # The file doesn't have any content stored on Drive.
    return nil
  end
end

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.