Create and manage folders

This page describes how to create, list, upload, delete, and get the metadata offolders in buckets withhierarchical namespace enabled.

Before you begin

Ensure that your bucket has hierarchical namespace enabled. For detailedinstructions about enabling hierarchical namespace on a bucket, seeCreatebuckets with hierarchical namespace enabled.

Create a folder

This section describes how to create a folder.

Roles required

In order to get the required permissions for creating folders, ask your administrator to grant you the Storage Object User (roles/storage.objectUser) IAM role on the bucket. This role contains thestorage.folders.create permission, which is required to create a folder.

For instructions on granting roles on buckets, seeUse IAM with buckets.

You might also be able to get this permission with othercustom roles orpredefined roles. For a more permissive role that lets you manage folders in addition to creating folders, ask your administrator to grant you any one of the following roles:

  • Storage Folder Admin (roles/storage.folderAdmin)
  • Storage Object Admin (roles/storage.objectAdmin)
  • Storage Admin (roles/storage.admin)

To see which roles are associated with which permissions, refer toIAM roles for Cloud Storage.

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the bucket list, click the name of the bucket you want to create the folder in.
  3. In theBucket details page, clickCreate folder to create an empty folder.
  4. In theName field, enter a name for your folder. For naming considerations, seeConsiderations.
  5. ClickCreate.

    Your newly created folder appears in theFolder browser pane.

Command line

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. In your development environment, run thegcloud storage folders create command:

    gcloud storage folders create --recursive gs://BUCKET_NAME/FOLDER_NAME

    Where:

    • BUCKET_NAME is the name of your bucket. For example,my-bucket.
    • FOLDER_NAME is the name of the folder you want to create. For example,my-folder/. For information about folder names, see thefolders overview documentation.
    • --recursive is a flag that automatically creates all non-existent parent folders along with the folder. This setting is optional when parent folders already exist.

    If the request is successful, the command returns the following message:

    Completed 1/1

Client Libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacestoragecontrol=google::cloud::storagecontrol_v2;[](storagecontrol::StorageControlClientclient,std::stringconst&bucket_name,std::stringconst&folder_id){autoconstparent=std::string{"projects/_/buckets/"}+bucket_name;autofolder=client.CreateFolder(parent,google::storage::control::v2::Folder{},folder_id);if(!folder)throwstd::move(folder).status();std::cout <<"Created folder: " <<folder->name() <<"\n";}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.Control.V2;usingSystem;publicclassStorageControlCreateFolderSample{publicFolderStorageControlCreateFolder(stringbucketName="your-unique-bucket-name",stringfolderName="your_folder_name"){StorageControlClientstorageControl=StorageControlClient.Create();varrequest=newCreateFolderRequest{// Set project to "_" to signify globally scoped bucketParent=BucketName.FormatProjectBucket("_",bucketName),FolderId=folderName};Folderfolder=storageControl.CreateFolder(request);Console.WriteLine($"Folder {folderName} created in bucket {bucketName}");returnfolder;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time"control"cloud.google.com/go/storage/control/apiv2""cloud.google.com/go/storage/control/apiv2/controlpb")// createFolder creates a folder in the bucket with the given name.funccreateFolder(wio.Writer,bucket,folderstring)error{// bucket := "bucket-name"// folder := "folder-name"ctx:=context.Background()client,err:=control.NewStorageControlClient(ctx)iferr!=nil{returnfmt.Errorf("NewStorageControlClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*30)defercancel()req:=&controlpb.CreateFolderRequest{Parent:fmt.Sprintf("projects/_/buckets/%v",bucket),FolderId:folder,}f,err:=client.CreateFolder(ctx,req)iferr!=nil{returnfmt.Errorf("CreateFolder(%q): %w",folder,err)}fmt.Fprintf(w,"created folder with path %q",f.Name)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.storage.control.v2.BucketName;importcom.google.storage.control.v2.CreateFolderRequest;importcom.google.storage.control.v2.Folder;importcom.google.storage.control.v2.StorageControlClient;importjava.io.IOException;publicfinalclassCreateFolder{publicstaticvoidcreateFolder(StringbucketName,StringfolderName)throwsIOException{// The name of the bucket// String bucketName = "your-unique-bucket-name";// The name of the folder within the bucket// String folderName = "your-unique-folder-name";try(StorageControlClientstorageControl=StorageControlClient.create()){CreateFolderRequestrequest=CreateFolderRequest.newBuilder()// Set project to "_" to signify globally scoped bucket.setParent(BucketName.format("_",bucketName)).setFolderId(folderName).build();FoldernewFolder=storageControl.createFolder(request);System.out.printf("Created folder: %s%n",newFolder.getName());}}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * TODO(developer): Uncomment these variables before running the sample. */// The name of your GCS bucket// const bucketName = 'bucketName';// The name of the folder to be created// const folderName = 'folderName';// Imports the Control libraryconst{StorageControlClient}=require('@google-cloud/storage-control').v2;// Instantiates a clientconstcontrolClient=newStorageControlClient();asyncfunctioncallCreateFolder(){constbucketPath=controlClient.bucketPath('_',bucketName);// Create the requestconstrequest={parent:bucketPath,folderId:folderName,};// Run requestconst[response]=awaitcontrolClient.createFolder(request);console.log(`Created folder:${response.name}.`);}callCreateFolder();

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;use Google\Cloud\Storage\Control\V2\CreateFolderRequest;/** * Create a new folder in an existing bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $folderName The name of your folder inside the bucket. *        (e.g. 'my-folder') */function create_folder(string $bucketName, string $folderName): void{    $storageControlClient = new StorageControlClient();    // Set project to "_" to signify global bucket    $formattedName = $storageControlClient->bucketName('_', $bucketName);    $request = new CreateFolderRequest([        'parent' => $formattedName,        'folder_id' => $folderName,    ]);    $folder = $storageControlClient->createFolder($request);    printf('Created folder: %s', $folder->getName());}

Python

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstorage_control_v2defcreate_folder(bucket_name:str,folder_name:str)->None:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the folder to be created# folder_name = "folder-name"storage_control_client=storage_control_v2.StorageControlClient()# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.project_path=storage_control_client.common_project_path("_")bucket_path=f"{project_path}/buckets/{bucket_name}"request=storage_control_v2.CreateFolderRequest(parent=bucket_path,folder_id=folder_name,)response=storage_control_client.create_folder(request=request)print(f"Created folder:{response.name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defcreate_folderbucket_name:,folder_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the folder to be created# folder_name = "folder-name"require"google/cloud/storage/control"storage_control=Google::Cloud::Storage::Control.storage_control# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.bucket_path=storage_control.bucket_pathproject:"_",bucket:bucket_namerequest=Google::Cloud::Storage::Control::V2::CreateFolderRequest.newparent:bucket_path,folder_id:folder_nameresponse=storage_control.create_folderrequestputs"Created folder:#{response.name}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a JSON file that contains the settings for the folder, which must include aname for the folder. See theFolders: Insert documentation for a complete list of settings. The following are required settings to include:
    {"name":"FOLDER_NAME",}

    WhereFOLDER_NAME is the name of the folder you want to create. For example,my-folder/. For information about folder names, see thefolders overview documentation.

  3. UsecURL to call theJSON API:
    curl -X POST --data-binary @JSON_FILE_NAME \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  -H "Content-Type: application/json" \  "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders?recursive=true"

    Where:

    • JSON_FILE_NAME is the name of the JSON file that contains the settings for the folder.
    • BUCKET_NAME is the name of the bucket where you want to create the folder.
    • recursive is set to true to automatically create all the non-existent parent folders along with the folder. This setting is optional when parent folders already exist.

List folders

This section describes how to list folders.

Roles required

In order to get the required permissions for listing folders, ask your administrator to grant you the Storage Object Viewer (roles/storage.objectViewer) IAM role on the bucket. This role contains thestorage.folders.list permission, which is required to list folders.

For instructions on granting roles on buckets, seeUse IAM with buckets.

You might also be able to get this permission with othercustom roles orpredefined roles. For a more permissive role that lets you manage folders in addition to listing folders, ask your administrator to grant you any one of the following roles:

  • Storage Folder Admin (roles/storage.folderAdmin)
  • Storage Object Admin (roles/storage.objectAdmin)
  • Storage Object User (roles/storage.objectUser)
  • Storage Admin (roles/storage.admin)

To see which roles are associated with which permissions, refer toIAM roles for Cloud Storage.

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the bucket list, click the name of the bucket whose folders you want tolist.

  3. From theFolder browser pane, use the expander arrow to expand thelist of folders within your bucket.

    A list displays the folders, simulated folders, and managed folders in your bucket.

Command line

To list all folders in a bucket, run thegcloud storage folders list command:

gcloud storage folders list gs://BUCKET_NAME/

Where:

  • BUCKET_NAME is the name of the bucket thatcontains the folders you want to list. For example,my-bucket.

A successful response looks like the following example:

bucket: hns-bucketid: hns-bucket/A/kind: storage#foldername: A/selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/AtimeCreated: '2023-05-05T16:32:08.878000+00:00'updated: '2023-05-05T16:32:08.878000+00:00'---bucket: hns-bucketid: hns-bucket/B/kind: storage#foldername: B/selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/BtimeCreated: '2023-05-05T16:32:08.878000+00:00'updated: '2023-05-05T16:32:08.878000+00:00'---bucket: hns-bucketid: hns-bucket/B/D/kind: storage#foldername: D/selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B/DtimeCreated: '2023-05-05T16:32:08.878000+00:00'updated: '2023-05-05T16:32:08.878000+00:00'---bucket: hns-bucketid: hns-bucket/C/kind: storage#foldername: C/selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/CtimeCreated: '2023-05-05T16:32:08.878000+00:00'updated: '2023-05-05T16:32:08.878000+00:00'---bucket: hns-bucketid: hns-bucket/C/E/kind: storage#foldername: E/selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C/EtimeCreated: '2023-05-05T16:32:08.878000+00:00'updated: '2023-05-05T16:32:08.878000+00:00'...

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacestoragecontrol=google::cloud::storagecontrol_v2;[](storagecontrol::StorageControlClientclient,std::stringconst&bucket_name){autoconstparent=std::string{"projects/_/buckets/"}+bucket_name;for(autofolder:client.ListFolders(parent)){if(!folder)throwstd::move(folder).status();std::cout <<folder->name() <<"\n";}std::cout <<bucket_name <<std::endl;}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.Control.V2;usingSystem;usingSystem.Collections.Generic;publicclassStorageControlListFoldersSample{publicIEnumerable<Folder>StorageControlListFolders(stringbucketName="your-unique-bucket-name"){StorageControlClientstorageControl=StorageControlClient.Create();// Use "_" for project ID to signify globally scoped bucketstringbucketResourceName=BucketName.FormatProjectBucket("_",bucketName);varfolders=storageControl.ListFolders(bucketResourceName);foreach(varfolderinfolders){Console.Write(folder.Name);}returnfolders;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time"control"cloud.google.com/go/storage/control/apiv2""cloud.google.com/go/storage/control/apiv2/controlpb""google.golang.org/api/iterator")// listFolders lists all folders present in the bucket.funclistFolders(wio.Writer,bucketstring)error{// bucket := "bucket-name"// folder := "folder-name"ctx:=context.Background()client,err:=control.NewStorageControlClient(ctx)iferr!=nil{returnfmt.Errorf("NewStorageControlClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*30)defercancel()// Construct bucket path for a bucket containing folders.bucketPath:=fmt.Sprintf("projects/_/buckets/%v",bucket)// List all folders present.req:=&controlpb.ListFoldersRequest{Parent:bucketPath,}it:=client.ListFolders(ctx,req)for{f,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnfmt.Errorf("ListFolders(%q): %w",bucketPath,err)}fmt.Fprintf(w,"got folder %v\n",f.Name)}returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.storage.control.v2.BucketName;importcom.google.storage.control.v2.Folder;importcom.google.storage.control.v2.ListFoldersRequest;importcom.google.storage.control.v2.StorageControlClient;importjava.io.IOException;publicfinalclassListFolders{publicstaticvoidlistFolders(StringbucketName)throwsIOException{// The name of the bucket// String bucketName = "your-unique-bucket-name";try(StorageControlClientstorageControl=StorageControlClient.create()){ListFoldersRequestrequest=ListFoldersRequest.newBuilder()// Set project to "_" to signify globally scoped bucket.setParent(BucketName.format("_",bucketName)).build();Iterable<Folder>folders=storageControl.listFolders(request).iterateAll();for(Folderfolder:folders){System.out.printf("Found folder: %s%n",folder.getName());}}}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * TODO(developer): Uncomment these variables before running the sample. */// The name of your GCS bucket// const bucketName = 'bucketName';// Imports the Control libraryconst{StorageControlClient}=require('@google-cloud/storage-control').v2;// Instantiates a clientconstcontrolClient=newStorageControlClient();asyncfunctioncallListFolders(){constbucketPath=controlClient.bucketPath('_',bucketName);// Create the requestconstrequest={parent:bucketPath,};// Run requestconst[folders]=awaitcontrolClient.listFolders(request);for(constcurFolderoffolders){console.log(curFolder.name);}}callListFolders();

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;use Google\Cloud\Storage\Control\V2\ListFoldersRequest;/** * List folders in an existing bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') */function list_folders(string $bucketName): void{    $storageControlClient = new StorageControlClient();    // Set project to "_" to signify global bucket    $formattedName = $storageControlClient->bucketName('_', $bucketName);    $request = new ListFoldersRequest([        'parent' => $formattedName,    ]);    $folders = $storageControlClient->listFolders($request);    foreach ($folders as $folder) {        printf('Folder name: %s' . PHP_EOL, $folder->getName());    }}

Python

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstorage_control_v2deflist_folders(bucket_name:str)->None:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"storage_control_client=storage_control_v2.StorageControlClient()# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.project_path=storage_control_client.common_project_path("_")bucket_path=f"{project_path}/buckets/{bucket_name}"request=storage_control_v2.ListFoldersRequest(parent=bucket_path,)page_result=storage_control_client.list_folders(request=request)forfolderinpage_result:print(folder)print(f"Listed folders in bucket{bucket_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

deflist_foldersbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage/control"storage_control=Google::Cloud::Storage::Control.storage_control# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.bucket_path=storage_control.bucket_pathproject:"_",bucket:bucket_namerequest=Google::Cloud::Storage::Control::V2::ListFoldersRequest.newparent:bucket_pathresponse=storage_control.list_foldersrequestputsresponse.response.foldersend

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with arequest to list folders:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders"

    WhereBUCKET_NAME is the name of the bucketthat contains the folders you want to list. For example,my-bucket.

Upload a folder

This section describes how to upload folders to a bucket.

Roles required

In order to get the required permissions for uploading folders, ask your administrator to grant you the Storage Object User (roles/storage.objectUser) IAM role on the bucket. This role contains thestorage.folders.create permission, which is required to upload a folder.

For instructions on granting roles on buckets, seeUse IAM with buckets.

You might also be able to get this permission with othercustom roles orpredefined roles. For a more permissive role that lets you manage folders in addition to uploading folders, ask your administrator to grant you any one of the following roles:

  • Storage Folder Admin (roles/storage.folderAdmin)
  • Storage Object Admin (roles/storage.objectAdmin)
  • Storage Admin (roles/storage.admin)

To see which roles are associated with which permissions, refer toIAM roles for Cloud Storage.

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket you want to upload the folder to.

  3. In theBucket details tab, perform one of the following actions:

    • Drag folders from your desktop or file managerto the main pane in the Google Cloud console.

    • ClickUpload > Upload folder, select the folder that you want to upload in the dialog that appears, then clickOpen.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.

Command line

Use thegcloud storage cp command with the--recursive flag:

gcloud storage cp --recursiveFOLDER_LOCATION gs://DESTINATION_BUCKET_NAME

Where:

  • FOLDER_LOCATION is the local path to yourfolder you want to upload. For example,../uploads/my-folder/.

  • DESTINATION_BUCKET_NAME is the name of thebucket to which you are uploading your folder. For example,my-bucket.

If successful, the response looks like the following example:

Copying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.pngCopying file://DIR/OBJ1 at 10.06.32 PM.png to gs://BUCKET_NAME/DIR/OBJ1 at 10.06.32 PM.pngCompleted files 2/2 | 1.7MiB/1.7MiB

Delete a folder

This section describes how to delete folders.

Roles required

In order to get the required permissions for deleting folders, ask your administrator to grant you the Storage Object User (roles/storage.objectUser) IAM role on the bucket. This role contains the following permissions, which are required to delete a folder:

  • storage.folders.delete
  • storage.managedFolders.delete (Only required if a managed folder exists with the same path as the folder)
  • For instructions on granting roles on buckets, seeUse IAM with buckets.

    You might also be able to get these permissions with othercustom roles orpredefined roles. For a more permissive role that lets you manage folders in addition to deleting folders, ask your administrator to grant you any one of the following roles:

    • Storage Folder Admin (roles/storage.folderAdmin)
    • Storage Object Admin (roles/storage.objectAdmin)
    • Storage Admin (roles/storage.admin)

    To see which roles are associated with which permissions, refer toIAM roles for Cloud Storage.

Note: If you delete a folder that has amanaged folder at the same path,the managed folder is also deleted. If the delete request fails to delete themanaged folder, you can see the managed folder name, even if you don't haveexplicitstorage.managedFolders.get orstorage.managedFolders.listpermissions. The managed folder name appears in the error message and theCloud Audit Logs of the failed request. When you grant thestorage.folders.delete permission, consider that on failure of the folderdeletion request the existence of the managed folder is revealed.

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the bucket list, click the name of the bucket whose folders you want to delete.

  3. From theFolder browser pane, use the expander arrow to expand thelist of folders within your bucket.

  4. Find the folder you want to delete.

  5. Click the folder'sMoreactions menu.

  6. ClickDelete folder.

  7. To confirm that you want to delete the folder, typeDELETE inDelete field.

  8. ClickDelete.

    The folder and its contents, including stored objects and othermanaged folders, are deleted from your Cloud Storage bucket.

Command line

To delete an empty folder, run thegcloud storage folders delete command:

gcloud storage folders delete gs://BUCKET_NAME/FOLDER_NAME

Where:

  • BUCKET_NAME is the name of the bucket. For example,my-bucket.

  • FOLDER_NAME is the name of the folder you want to delete. For example,my-folder/.

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacestoragecontrol=google::cloud::storagecontrol_v2;[](storagecontrol::StorageControlClientclient,std::stringconst&bucket_name,std::stringconst&folder_id){autoconstname=std::string{"projects/_/buckets/"}+bucket_name+"/folders/"+folder_id;autostatus=client.DeleteFolder(name);if(!status.ok())throwstd::move(status);std::cout <<"Deleted folder: " <<folder_id <<"\n";}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.Control.V2;usingSystem;publicclassStorageControlDeleteFolderSample{publicvoidStorageControlDeleteFolder(stringbucketName="your-unique-bucket-name",stringfolderName="your_folder_name"){StorageControlClientstorageControl=StorageControlClient.Create();stringfolderResourceName=// Set project to "_" to signify globally scoped bucketFolderName.FormatProjectBucketFolder("_",bucketName,folderName);storageControl.DeleteFolder(folderResourceName);Console.WriteLine($"Deleted folder {folderName} from bucket {bucketName}");}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time"control"cloud.google.com/go/storage/control/apiv2""cloud.google.com/go/storage/control/apiv2/controlpb")// deleteFolder deletes the folder with the given name.funcdeleteFolder(wio.Writer,bucket,folderstring)error{// bucket := "bucket-name"// folder := "folder-name"ctx:=context.Background()client,err:=control.NewStorageControlClient(ctx)iferr!=nil{returnfmt.Errorf("NewStorageControlClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*30)defercancel()// Construct folder path including the bucket name.folderPath:=fmt.Sprintf("projects/_/buckets/%v/folders/%v",bucket,folder)req:=&controlpb.DeleteFolderRequest{Name:folderPath,}iferr:=client.DeleteFolder(ctx,req);err!=nil{returnfmt.Errorf("DeleteFolder(%q): %w",folderPath,err)}fmt.Fprintf(w,"deleted folder %q",folderPath)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.storage.control.v2.DeleteFolderRequest;importcom.google.storage.control.v2.FolderName;importcom.google.storage.control.v2.StorageControlClient;importjava.io.IOException;publicfinalclassDeleteFolder{publicstaticvoiddeleteFolder(StringbucketName,StringfolderName)throwsIOException{// The name of the bucket// String bucketName = "your-unique-bucket-name";// The name of the folder within the bucket// String folderName = "your-unique-folder-name";try(StorageControlClientstorageControl=StorageControlClient.create()){// Set project to "_" to signify globally scoped bucketStringfolderResourceName=FolderName.format("_",bucketName,folderName);DeleteFolderRequestrequest=DeleteFolderRequest.newBuilder().setName(folderResourceName).build();storageControl.deleteFolder(request);System.out.printf("Deleted folder: %s%n",folderResourceName);}}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * TODO(developer): Uncomment these variables before running the sample. */// The name of your GCS bucket// const bucketName = 'bucketName';// The name of the folder to be deleted// const folderName = 'folderName';// Imports the Control libraryconst{StorageControlClient}=require('@google-cloud/storage-control').v2;// Instantiates a clientconstcontrolClient=newStorageControlClient();asyncfunctioncallDeleteFolder(){constfolderPath=controlClient.folderPath('_',bucketName,folderName);// Create the requestconstrequest={name:folderPath,};// Run requestawaitcontrolClient.deleteFolder(request);console.log(`Deleted folder:${folderName}.`);}callDeleteFolder();

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;use Google\Cloud\Storage\Control\V2\DeleteFolderRequest;/** * Delete a folder in an existing bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $folderName The name of your folder inside the bucket. *        (e.g. 'my-folder') */function delete_folder(string $bucketName, string $folderName): void{    $storageControlClient = new StorageControlClient();    // Set project to "_" to signify global bucket    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);    $request = new DeleteFolderRequest([        'name' => $formattedName,    ]);    $storageControlClient->deleteFolder($request);    printf('Deleted folder: %s', $folderName);}

Python

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstorage_control_v2defdelete_folder(bucket_name:str,folder_name:str)->None:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the folder to be deleted# folder_name = "folder-name"storage_control_client=storage_control_v2.StorageControlClient()# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.folder_path=storage_control_client.folder_path(project="_",bucket=bucket_name,folder=folder_name)request=storage_control_v2.DeleteFolderRequest(name=folder_path,)storage_control_client.delete_folder(request=request)print(f"Deleted folder{folder_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defdelete_folderbucket_name:,folder_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"## Name of the folder you want to delete# folder_name = "name-of-the-folder"require"google/cloud/storage/control"storage_control=Google::Cloud::Storage::Control.storage_control# The storage folder path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.folder_path=storage_control.folder_pathproject:"_",bucket:bucket_name,folder:folder_namerequest=Google::Cloud::Storage::Control::V2::DeleteFolderRequest.newname:folder_pathstorage_control.delete_folderrequestputs"Deleted folder:#{folder_name}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with aDELETE Folderrequest:

    curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders/FOLDER_NAME"

    Where:

    • BUCKET_NAME is the name of the bucketthat contains the folder you want to delete. For example,my-bucket.

    • FOLDER_NAME is the URL-encoded nameof the folder you want to delete. For example,my-folder/,URL-encoded asmy-folder%2F.

Get the metadata of a folder

This section describes how to get themetadata of a folder.

Roles required

In order to get the required permissions for getting the metadata of a folder, ask your administrator to grant you the Storage Object Viewer (roles/storage.objectViewer) IAM role on the bucket. This role contains thestorage.folders.get permission, which is required to get the metadata of a folder.

For instructions on granting roles on buckets, seeUse IAM with buckets.

You might also be able to get this permission with othercustom roles orpredefined roles. For a more permissive role that lets you manage folders in addition to getting the metadata of a folder, ask your administrator to grant you any one of the following roles:

  • Storage Folder Admin (roles/storage.folderAdmin)
  • Storage Object Admin (roles/storage.objectAdmin)
  • Storage Object User (roles/storage.objectUser)
  • Storage Admin (roles/storage.admin)

To see which roles are associated with which permissions, refer toIAM roles for Cloud Storage.

Command line

To get the metadata of a folder, run thegcloud storage folders describe command:

gcloud storage folders describe gs://BUCKET_NAME/FOLDER_NAME

Where:

  • BUCKET_NAME is the name of the bucket thatcontains the folder whose metadata you want to retrieve. For example,my-bucket.
  • FOLDER_NAME is the name of the folder whose metadatayou want to retrieve. For example,my-folder/.

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacestoragecontrol=google::cloud::storagecontrol_v2;[](storagecontrol::StorageControlClientclient,std::stringconst&bucket_name,std::stringconst&folder_id){autoconstname=std::string{"projects/_/buckets/"}+bucket_name+"/folders/"+folder_id;autofolder=client.GetFolder(name);if(!folder)throwstd::move(folder).status();std::cout <<"Got folder: " <<folder->name() <<"\n";}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.Control.V2;usingSystem;publicclassStorageControlGetFolderSample{publicFolderStorageControlGetFolder(stringbucketName="your-unique-bucket-name",stringfolderName="your_folder_name"){StorageControlClientstorageControl=StorageControlClient.Create();stringfolderResourceName=// Set project to "_" to signify globally scoped bucketFolderName.FormatProjectBucketFolder("_",bucketName,folderName);Folderfolder=storageControl.GetFolder(folderResourceName);Console.WriteLine($"Got folder: {folder.Name}");returnfolder;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time"control"cloud.google.com/go/storage/control/apiv2""cloud.google.com/go/storage/control/apiv2/controlpb")// getFolder gets metadata for the folder with the given name.funcgetFolder(wio.Writer,bucket,folderstring)error{// bucket := "bucket-name"// folder := "folder-name"ctx:=context.Background()client,err:=control.NewStorageControlClient(ctx)iferr!=nil{returnfmt.Errorf("NewStorageControlClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*30)defercancel()// Construct folder path including the bucket name.folderPath:=fmt.Sprintf("projects/_/buckets/%v/folders/%v",bucket,folder)req:=&controlpb.GetFolderRequest{Name:folderPath,}f,err:=client.GetFolder(ctx,req)iferr!=nil{returnfmt.Errorf("GetFolder(%q): %w",folderPath,err)}fmt.Fprintf(w,"got folder metadata: %+v",f)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.storage.control.v2.Folder;importcom.google.storage.control.v2.FolderName;importcom.google.storage.control.v2.GetFolderRequest;importcom.google.storage.control.v2.StorageControlClient;importjava.io.IOException;publicfinalclassGetFolder{publicstaticvoidgetFolder(StringbucketName,StringfolderName)throwsIOException{// The name of the bucket// String bucketName = "your-unique-bucket-name";// The name of the folder within the bucket// String folderName = "your-unique-folder-name";try(StorageControlClientstorageControl=StorageControlClient.create()){GetFolderRequestrequest=GetFolderRequest.newBuilder()// Set project to "_" to signify globally scoped bucket.setName(FolderName.format("_",bucketName,folderName)).build();FoldernewFolder=storageControl.getFolder(request);System.out.printf("Got folder: %s%n",newFolder.getName());}}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * TODO(developer): Uncomment these variables before running the sample. */// The name of your GCS bucket// const bucketName = 'bucketName';// The name of the folder to get// const folderName = 'folderName';// Imports the Control libraryconst{StorageControlClient}=require('@google-cloud/storage-control').v2;// Instantiates a clientconstcontrolClient=newStorageControlClient();asyncfunctioncallGetFolder(){constfolderPath=controlClient.folderPath('_',bucketName,folderName);// Create the requestconstrequest={name:folderPath,};// Run requestconst[response]=awaitcontrolClient.getFolder(request);console.log(`Got folder:${response.name}.`);}callGetFolder();

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;use Google\Cloud\Storage\Control\V2\GetFolderRequest;/** * Get a folder in an existing bucket. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $folderName The name of your folder inside the bucket. *        (e.g. 'my-folder') */function get_folder(string $bucketName, string $folderName): void{    $storageControlClient = new StorageControlClient();    // Set project to "_" to signify global bucket    $formattedName = $storageControlClient->folderName('_', $bucketName, $folderName);    $request = new GetFolderRequest([        'name' => $formattedName,    ]);    $folder = $storageControlClient->getFolder($request);    printf($folder->getName());}

Python

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstorage_control_v2defget_folder(bucket_name:str,folder_name:str)->None:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the folder# folder_name = "folder-name"storage_control_client=storage_control_v2.StorageControlClient()# The storage bucket path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.folder_path=storage_control_client.folder_path(project="_",bucket=bucket_name,folder=folder_name)request=storage_control_v2.GetFolderRequest(name=folder_path,)response=storage_control_client.get_folder(request=request)print(f"Got folder:{response.name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defget_folderbucket_name:,folder_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The name of the folder to be created# folder_name = "folder-name"require"google/cloud/storage/control"storage_control=Google::Cloud::Storage::Control.storage_control# The storage folder path uses the global access pattern, in which the "_"# denotes this bucket exists in the global namespace.folder_path=storage_control.folder_pathproject:"_",bucket:bucket_name,folder:folder_namerequest=Google::Cloud::Storage::Control::V2::GetFolderRequest.newname:folder_pathresponse=storage_control.get_folderrequestputs"Got folder#{response.name}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with aGETFolder request:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/folders/FOLDER_NAME"

    Where:

    • BUCKET_NAME is the name of the bucketthat contains the folder whose metadata you want to retrieve. For example,my-bucket.

    • FOLDER_NAME is the URL-encoded nameof the folder whose metadata you want to retrieve. For example,my-folder/, URL-encoded asmy-folder%2F.

Manage access on a folder

This section describes how to manage access on your folder by settingIdentity and Access Management (IAM) policies, so you can get fine-grained accesscontrol over specific groups of objects within a bucket.

To manage access on your folder, follow these steps:

  1. Enable management on your folder by creating amanaged folderwith the same name as your existing folder. For detailed instructions, seeCreate a managed folder.

  2. Set and manage Identity and Access Management (IAM) policies on the managed folderyou created.

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how Cloud Storage performs in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Try Cloud Storage free

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-17 UTC.