Create and populate folders Stay organized with collections Save and categorize content based on your preferences.
Folders are files that only contain metadata and can be used to organize filesin Google Drive. They have the following properties:
- A folder is a file with theMIME type
application/vnd.google-apps.folderand it has no extension. - The alias
rootcan be used to refer to the root folder anywhere a file IDis provided.
For more information about Drive folder limits, seeFile andfolder limits.
This guide explains how to perform some basic folder-related tasks.
Create a folder
To create a folder, use thefiles.create()method with themimeType ofapplication/vnd.google-apps.folder and aname.The following code sample shows how to create a folder using a client library:
files.insert method. You can find codesamples inGitHub.Learn how tomigrate to Drive API v3.Java
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate use of Drive's create folder API */publicclassCreateFolder{/** * Create new folder. * * @return Inserted folder id if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */publicstaticStringcreateFolder()throwsIOException{// Load pre-authorized user credentials from the environment.// TODO(developer) - See https://developers.google.com/identity for// guides on implementing OAuth2 for your application.GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();// File's metadata.FilefileMetadata=newFile();fileMetadata.setName("Test");fileMetadata.setMimeType("application/vnd.google-apps.folder");try{Filefile=service.files().create(fileMetadata).setFields("id").execute();System.out.println("Folder ID: "+file.getId());returnfile.getId();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to create folder: "+e.getDetails());throwe;}}}
Python
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefcreate_folder():"""Create a folder and prints the folder ID Returns : Folder Id Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# create drive api clientservice=build("drive","v3",credentials=creds)file_metadata={"name":"Invoices","mimeType":"application/vnd.google-apps.folder",}# pylint: disable=maybe-no-memberfile=service.files().create(body=file_metadata,fields="id").execute()print(f'Folder ID: "{file.get("id")}".')returnfile.get("id")exceptHttpErroraserror:print(f"An error occurred:{error}")returnNoneif__name__=="__main__":create_folder()
Node.js
import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Creates a new folder in Google Drive. * @return {Promise<string|null|undefined>} The ID of the created folder. */asyncfunctioncreateFolder(){// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Drive API client (v3).constservice=google.drive({version:'v3',auth});// The metadata for the new folder.constfileMetadata={name:'Invoices',mimeType:'application/vnd.google-apps.folder',};// Create the new folder.constfile=awaitservice.files.create({requestBody:fileMetadata,fields:'id',});// Print the ID of the new folder.console.log('Folder Id:',file.data.id);returnfile.data.id;}
PHP
<?phpuse Google\Client;use Google\Service\Drive;function createFolder(){ try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); $fileMetadata = new Drive\DriveFile(array( 'name' => 'Invoices', 'mimeType' => 'application/vnd.google-apps.folder')); $file = $driveService->files->create($fileMetadata, array( 'fields' => 'id')); printf("Folder ID: %s\n", $file->id); return $file->id; }catch(Exception $e) { echo "Error Message: ".$e; }}
.NET
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use of Drive create folder API.publicclassCreateFolder{/// <summary>/// Creates a new folder./// </summary>/// <returns>created folder id, null otherwise</returns>publicstaticstringDriveCreateFolder(){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// File metadatavarfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="Invoices",MimeType="application/vnd.google-apps.folder"};// Create a new folder on drive.varrequest=service.Files.Create(fileMetadata);request.Fields="id";varfile=request.Execute();// Prints the created folder id.Console.WriteLine("Folder ID: "+file.Id);returnfile.Id;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
Create a file in a specific folder
To create a file in a specific folder, use thefiles.create() method and specify the folder ID in theparents property of the file.
Theparents property holds the ID of the parent folder containing the file.Theparents property can be used when creating files in a top-level folder orany other folder.
A file can only have one parent folder. Specifying multiple parents isn'tsupported. If theparents field isn't specified, the file is placed directlyin the user's My Drive folder.
The following code sample shows how to create a file in a specific folder usinga client library:
Note: If you're using the older Drive API v2, use thefiles.insert method. You can find codesamples inGitHub.Learn how tomigrate to Drive API v3.Java
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.FileContent;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;importjava.util.Collections;/* Class to demonstrate Drive's upload to folder use-case. */publicclassUploadToFolder{/** * Upload a file to the specified folder. * * @param realFolderId Id of the folder. * @return Inserted file metadata if successful, {@code null} otherwise. * @throws IOException if service account credentials file not found. */publicstaticFileuploadToFolder(StringrealFolderId)throwsIOException{// Load pre-authorized user credentials from the environment.// TODO(developer) - See https://developers.google.com/identity for// guides on implementing OAuth2 for your application.GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();// File's metadata.FilefileMetadata=newFile();fileMetadata.setName("photo.jpg");fileMetadata.setParents(Collections.singletonList(realFolderId));java.io.FilefilePath=newjava.io.File("files/photo.jpg");FileContentmediaContent=newFileContent("image/jpeg",filePath);try{Filefile=service.files().create(fileMetadata,mediaContent).setFields("id, parents").execute();System.out.println("File ID: "+file.getId());returnfile;}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to upload file: "+e.getDetails());throwe;}}}
Python
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrorfromgoogleapiclient.httpimportMediaFileUploaddefupload_to_folder(folder_id):"""Upload a file to the specified folder and prints file ID, folder ID Args: Id of the folder Returns: ID of the file uploaded Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# create drive api clientservice=build("drive","v3",credentials=creds)file_metadata={"name":"photo.jpg","parents":[folder_id]}media=MediaFileUpload("download.jpeg",mimetype="image/jpeg",resumable=True)# pylint: disable=maybe-no-memberfile=(service.files().create(body=file_metadata,media_body=media,fields="id").execute())print(f'File ID: "{file.get("id")}".')returnfile.get("id")exceptHttpErroraserror:print(f"An error occurred:{error}")returnNoneif__name__=="__main__":upload_to_folder(folder_id="1s0oKEZZXjImNngxHGnY0xed6Mw-tvspu")
Node.js
importfsfrom'node:fs';import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Uploads a file to the specified folder. * @param {string} folderId The ID of the folder to upload the file to. * @return {Promise<string>} The ID of the uploaded file. */asyncfunctionuploadToFolder(folderId){// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Drive API client (v3).constservice=google.drive({version:'v3',auth});// The request body for the file to be uploaded.constrequestBody={name:'photo.jpg',parents:[folderId],};// The media content to be uploaded.constmedia={mimeType:'image/jpeg',body:fs.createReadStream('files/photo.jpg'),};// Upload the file to the specified folder.constfile=awaitservice.files.create({requestBody,media,fields:'id',});// Print the ID of the uploaded file.console.log('File Id:',file.data.id);if(!file.data.id){thrownewError('File ID not found.');}returnfile.data.id;}
PHP
<?phpuse Google\Client;use Google\Service\Drive;function uploadToFolder($folderId){ try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); $fileMetadata = new Drive\DriveFile(array( 'name' => 'photo.jpg', 'parents' => array($folderId) )); $content = file_get_contents('../files/photo.jpg'); $file = $driveService->files->create($fileMetadata, array( 'data' => $content, 'mimeType' => 'image/jpeg', 'uploadType' => 'multipart', 'fields' => 'id')); printf("File ID: %s\n", $file->id); return $file->id; } catch (Exception $e) { echo "Error Message: " . $e; }}require_once 'vendor/autoload.php';uploadToFolder();
.NET
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use of Drive upload to folder.publicclassUploadToFolder{/// <summary>/// Upload a file to the specified folder./// </summary>/// <param name="filePath">Image path to upload.</param>/// <param name="folderId">Id of the folder.</param>/// <returns>Inserted file metadata if successful, null otherwise</returns>publicstaticGoogle.Apis.Drive.v3.Data.FileDriveUploadToFolder(stringfilePath,stringfolderId){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Upload file photo.jpg in specified folder on drive.varfileMetadata=newGoogle.Apis.Drive.v3.Data.File(){Name="photo.jpg",Parents=newList<string>{folderId}};FilesResource.CreateMediaUploadrequest;// Create a new file on drive.using(varstream=newFileStream(filePath,FileMode.Open)){// Create a new file, with metadata and stream.request=service.Files.Create(fileMetadata,stream,"image/jpeg");request.Fields="id";request.Upload();}varfile=request.ResponseBody;// Prints the uploaded file id.Console.WriteLine("File ID: "+file.Id);returnfile;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}elseif(eisFileNotFoundException){Console.WriteLine("File not found");}elseif(eisDirectoryNotFoundException){Console.WriteLine("Directory Not found");}else{throw;}}returnnull;}}}
Move files between folders
To move files, you must update the ID of theparents property.
To add or remove parents for an existing file, use thefiles.update() method with either theaddParents andremoveParents query parameters.
A file can only have one parent folder. Specifying multiple parents isn'tsupported.
Warning: Even though a folder is a type of file, you can't move a folder from MyDrive into a shared drive by updating theaddParents parameter.Attempting to do so returns ateamDrivesFolderMoveInNotSupported HTTP statuscode response. For more information and potential workarounds, seeResolveerrorsThe following code sample shows how to move a file between folders using aclient library:
Java
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.File;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;importjava.util.List;/* Class to demonstrate use case for moving file to folder.*/publicclassMoveFileToFolder{/** * @param fileId Id of file to be moved. * @param folderId Id of folder where the fill will be moved. * @return list of parent ids for the file. */publicstaticList<String>moveFileToFolder(StringfileId,StringfolderId)throwsIOException{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();// Retrieve the existing parents to removeFilefile=service.files().get(fileId).setFields("parents").execute();StringBuilderpreviousParents=newStringBuilder();for(Stringparent:file.getParents()){previousParents.append(parent);previousParents.append(',');}try{// Move the file to the new folderfile=service.files().update(fileId,null).setAddParents(folderId).setRemoveParents(previousParents.toString()).setFields("id, parents").execute();returnfile.getParents();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to move file: "+e.getDetails());throwe;}}}
Python
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordefmove_file_to_folder(file_id,folder_id):"""Move specified file to the specified folder. Args: file_id: Id of the file to move. folder_id: Id of the folder Print: An object containing the new parent folder and other meta data Returns : Parent Ids for the file Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# call drive api clientservice=build("drive","v3",credentials=creds)# pylint: disable=maybe-no-member# Retrieve the existing parents to removefile=service.files().get(fileId=file_id,fields="parents").execute()previous_parents=",".join(file.get("parents"))# Move the file to the new folderfile=(service.files().update(fileId=file_id,addParents=folder_id,removeParents=previous_parents,fields="id, parents",).execute())returnfile.get("parents")exceptHttpErroraserror:print(f"An error occurred:{error}")returnNoneif__name__=="__main__":move_file_to_folder(file_id="1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9",folder_id="1jvTFoyBhUspwDncOTB25kb9k0Fl0EqeN",)
Node.js
import{GoogleAuth}from'google-auth-library';import{google}from'googleapis';/** * Moves a file to a new folder in Google Drive. * @param {string} fileId The ID of the file to move. * @param {string} folderId The ID of the folder to move the file to. * @return {Promise<number>} The status of the move operation. */asyncfunctionmoveFileToFolder(fileId,folderId){// Authenticate with Google and get an authorized client.// TODO (developer): Use an appropriate auth mechanism for your app.constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive',});// Create a new Drive API client (v3).constservice=google.drive({version:'v3',auth});// Get the file's metadata to retrieve its current parents.constfile=awaitservice.files.get({fileId,fields:'parents',});// Get the current parents as a comma-separated string.constpreviousParents=(file.data.parents??[]).join(',');// Move the file to the new folder.constresult=awaitservice.files.update({fileId,addParents:folderId,removeParents:previousParents,fields:'id, parents',});// Print the status of the move operation.console.log(result.status);returnresult.status;}
PHP
<?phpuse Google\Client;use Google\Service\Drive;use Google\Service\Drive\DriveFile;function moveFileToFolder($fileId,$folderId){ try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); $emptyFileMetadata = new DriveFile(); // Retrieve the existing parents to remove $file = $driveService->files->get($fileId, array('fields' => 'parents')); $previousParents = join(',', $file->parents); // Move the file to the new folder $file = $driveService->files->update($fileId, $emptyFileMetadata, array( 'addParents' => $folderId, 'removeParents' => $previousParents, 'fields' => 'id, parents')); return $file->parents; } catch(Exception $e) { echo "Error Message: ".$e; }}
.NET
usingGoogle;usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use-case of Drive move file to folder.publicclassMoveFileToFolder{/// <summary>/// Move specified file to the specified folder./// </summary>/// <param name="fileId">Id of file to be moved.</param>/// <param name="folderId">Id of folder where the fill will be moved.</param>/// <returns>list of parent ids for the file, null otherwise.</returns>publicstaticIList<string>DriveMoveFileToFolder(stringfileId,stringfolderId){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Retrieve the existing parents to removevargetRequest=service.Files.Get(fileId);getRequest.Fields="parents";varfile=getRequest.Execute();varpreviousParents=String.Join(",",file.Parents);// Move the file to the new foldervarupdateRequest=service.Files.Update(newGoogle.Apis.Drive.v3.Data.File(),fileId);updateRequest.Fields="id, parents";updateRequest.AddParents=folderId;updateRequest.RemoveParents=previousParents;file=updateRequest.Execute();returnfile.Parents;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}elseif(eisGoogleApiException){Console.WriteLine("File or Folder not found");}else{throw;}}returnnull;}}}
children andparentsresources can also facilitate the reorganization of files and folders.File and folder limits
Drive files and folders have some storage limits.
User-item limit
Each user can have up to 500 million items that were created by that account.When the limit is reached, the user can no longer create or upload items inDrive. They can still view and edit existing items. To createfiles again, users must permanently delete items or use a different account. Formore information, seeTrash or delete files andfolders.
Objects that count toward this limit are:
- Items created or uploaded by the user in Drive
- Items created by the user but now owned by someone else
- Items in the trash
- Shortcuts
- Third-party shortcuts
Objects that don't count toward this limit are:
- Permanently-deleted items
- Items shared with the user but owned by someone else
- Items owned by the user but created by someone else
Attempts to add more than 500 million items returns anactiveItemCreationLimitExceededHTTP status code response.
Note that service accounts can't own any files. Instead, they must upload filesand folders into shared drives, or use OAuth 2.0 to upload items on behalfof a human user.
Folder-item limit
Each folder in a user's My Drive has a limit of 500,000 items.This limit doesn't apply to the root folder of My Drive. Itemsthat count toward this limit are:
- Folders
- Files. All file types, regardless of file ownership.
- Shortcuts. Counts as a single item within a folder, even if the item itpoints to isn't within that folder. For more information, seeCreate ashortcut to a Drive file.
- Third-party shortcuts. Counts as a single item within a folder, even if theitem it points to isn't within that folder. For more information, seeCreate a shortcut file to content stored by yourapp.
For more information about folder limits, seeFolder limits inGoogle Drive.
Folder-depth limit
A user's My Drive can't contain more than 100 levels of nestedfolders. This means that a child folder cannot be stored under a folder that'smore than 99 levels deep. This limitation only applies to child folders. A childfile with aMIME type other thanapplication/vnd.google-apps.folder is exempt from this limitation.
For example, in the following diagram a new folder can be nested inside foldernumber 99 but not inside folder number 100. However, folder number 100 can storefiles like any other Drive folder:
Attempts to add more than 100 levels of folders returns amyDriveHierarchyDepthLimitExceededHTTP status code response.
files field in theGoogle Drive API that can return the depth of a folder. To determine the folderdepth, you must manually ascend the folder hierarchy.Related topics
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-11 UTC.