Gets a file's metadata or content by ID. Try it now or see an example.
If you provide the URL parameter alt=media
, then the response includes the file contents in the response body. Downloading content with alt=media
only works if the file is stored in Drive. To download Google Docs, Sheets, and Slides use files.export
instead. For further information on downloading files, refer to Download files.
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 )
|
includeLabels |
string |
A comma-separated list of IDs of labels to include in the labelInfo part of the response.
|
includePermissionsForView |
string |
Specifies which additional view's permissions to include in the response. Only 'published' is supported. |
projection |
string |
This parameter is deprecated and has no function.
Acceptable values are:
|
revisionId |
string |
Specifies the Revision ID that should be downloaded. Ignored unless alt=media is specified. |
supportsAllDrives |
boolean |
Whether the requesting application supports both My Drives and shared drives.
(Default: false )
|
supportsTeamDrives |
boolean |
Deprecated use supportsAllDrives instead.
(Default: false )
|
updateViewedDate |
boolean |
Deprecated: Use files.update with modifiedDateBehavior=noChange, updateViewedDate=true and an empty request body.
(Default: false )
|
Authorization
This request allows authorization with at least one of the following scopes:
Scope |
---|
https://www.googleapis.com/auth/drive |
https://www.googleapis.com/auth/drive.file |
https://www.googleapis.com/auth/drive.readonly |
https://www.googleapis.com/auth/drive.metadata.readonly |
https://www.googleapis.com/auth/drive.appdata |
https://www.googleapis.com/auth/drive.metadata |
https://www.googleapis.com/auth/drive.photos.readonly |
Some scopes are restricted and require a security assessment for your app to use them. For more information, see the authentication and authorization page.
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 the response includes the file contents in the response body. Downloading content with alt=media
only works if the file is stored in Drive. To download Google Docs, Sheets, and Slides use files.export
instead. For further information on downloading files, refer to 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 occurred: " + 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
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 ( "google.golang.org/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.