Create and manage folders

This page describes how to create, list, delete, and get metadata of folders in buckets with hierarchical namespace enabled.

Create a folder

This section describes how to create a folder.

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the bucket list, click the name of the bucket you want to create the folder in.
  3. In the Bucket details page, click Create folder to create an empty folder.
  4. In the Name field, enter a name for your folder. For naming considerations, see Considerations.
  5. Click Create.

    Your newly created folder appears in the Folder browser pane.

Command line

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

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud 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 the following 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 the folders 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 the Cloud Storage C++ API reference documentation.

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  auto folder = client.CreateFolder(
      parent, google::storage::control::v2::Folder{}, folder_id);
  if (!folder) throw std::move(folder).status();

  std::cout << "Created folder: " << folder->name() << "\n";
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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.
func createFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	req := &controlpb.CreateFolderRequest{
		Parent:   fmt.Sprintf("projects/_/buckets/%v", bucket),
		FolderId: folder,
	}
	f, err := client.CreateFolder(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateFolder(%q): %w", folder, err)
	}

	fmt.Fprintf(w, "created folder with path %q", f.Name)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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

import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.CreateFolderRequest;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class CreateFolder {

  public static void createFolder(String bucketName, String folderName) throws IOException {
    // 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 (StorageControlClient storageControl = StorageControlClient.create()) {

      CreateFolderRequest request =
          CreateFolderRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setParent(BucketName.format("_", bucketName))
              .setFolderId(folderName)
              .build();

      Folder newFolder = storageControl.createFolder(request);

      System.out.printf("Created folder: %s%n", newFolder.getName());
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callCreateFolder() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

  // Create the request
  const request = {
    parent: bucketPath,
    folderId: folderName,
  };

  // Run request
  const [response] = await controlClient.createFolder(request);
  console.log(`Created folder: ${response.name}.`);
}

callCreateFolder();

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 the Cloud Storage Python API reference documentation.

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

from google.cloud import storage_control_v2


def create_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 the Cloud Storage Ruby API reference documentation.

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

def create_folder bucket_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_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::CreateFolderRequest.new parent: bucket_path, folder_id: folder_name

  response = storage_control.create_folder request

  puts "Created folder: #{response.name}"
end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

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

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

  3. Use cURL to call the JSON 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.

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

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

  3. From the Folder browser pane, use the expander arrow to expand the list 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 the following command:

gcloud storage folders list gs://BUCKET_NAME/

Where:

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

A successful response looks like the following example:

bucket: hns-bucket
id: hns-bucket/A/
kind: storage#folder
name: A/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/A
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/
kind: storage#folder
name: B/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/B/D/
kind: storage#folder
name: D/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/B/D
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/
kind: storage#folder
name: C/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
---
bucket: hns-bucket
id: hns-bucket/C/E/
kind: storage#folder
name: E/
selfLink: https://www.googleapis.com/storage/v1/b/hns-bucket/f/C/E
timeCreated: '2023-05-05T16:32:08.878000+00:00'
updated: '2023-05-05T16:32:08.878000+00:00'
...

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  for (auto folder : client.ListFolders(parent)) {
    if (!folder) throw std::move(folder).status();
    std::cout << folder->name() << "\n";
  }

  std::cout << bucket_name << std::endl;
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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.
func listFolders(w io.Writer, bucket string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// 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()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListFolders(%q): %w", bucketPath, err)
		}
		fmt.Fprintf(w, "got folder %v\n", f.Name)
	}

	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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


import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.ListFoldersRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class ListFolders {

  public static void listFolders(String bucketName) throws IOException {
    // The name of the bucket
    // String bucketName = "your-unique-bucket-name";

    try (StorageControlClient storageControl = StorageControlClient.create()) {

      ListFoldersRequest request =
          ListFoldersRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setParent(BucketName.format("_", bucketName))
              .build();

      Iterable<Folder> folders = storageControl.listFolders(request).iterateAll();
      for (Folder folder : folders) {
        System.out.printf("Found folder: %s%n", folder.getName());
      }
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callListFolders() {
  const bucketPath = controlClient.bucketPath('_', bucketName);

  // Create the request
  const request = {
    parent: bucketPath,
  };

  // Run request
  const [folders] = await controlClient.listFolders(request);
  for (const curFolder of folders) {
    console.log(curFolder.name);
  }
}

callListFolders();

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 the Cloud Storage Python API reference documentation.

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

from google.cloud import storage_control_v2


def list_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)
    for folder in page_result:
        print(folder)

    print(f"Listed folders in bucket {bucket_name}")

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

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

def list_folders bucket_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_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::ListFoldersRequest.new parent: bucket_path

  response = storage_control.list_folders request

  puts response.response.folders
end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Use cURL to call the JSON API with a request to list folders:

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

    Where BUCKET_NAME is the name of the bucket that contains the folders you want to list. For example, my-bucket.

Delete a folder

This section describes how to delete folders.

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

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

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

  4. Find the folder you want to delete.

  5. Click the folder's More actions menu.

  6. Click Delete folder.

  7. To confirm that you want to delete the folder, type DELETE in Delete field.

  8. Click Delete.

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

Command line

To delete an empty folder, run the following 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 the Cloud Storage C++ API reference documentation.

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto status = client.DeleteFolder(name);
  if (!status.ok()) throw std::move(status);

  std::cout << "Deleted folder: " << folder_id << "\n";
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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.
func deleteFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// Construct folder path including the bucket name.
	folderPath := fmt.Sprintf("projects/_/buckets/%v/folders/%v", bucket, folder)

	req := &controlpb.DeleteFolderRequest{
		Name: folderPath,
	}
	if err := client.DeleteFolder(ctx, req); err != nil {
		return fmt.Errorf("DeleteFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "deleted folder %q", folderPath)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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


import com.google.storage.control.v2.DeleteFolderRequest;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class DeleteFolder {

  public static void deleteFolder(String bucketName, String folderName) throws IOException {
    // 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 (StorageControlClient storageControl = StorageControlClient.create()) {

      // Set project to "_" to signify globally scoped bucket
      String folderResourceName = FolderName.format("_", bucketName, folderName);
      DeleteFolderRequest request =
          DeleteFolderRequest.newBuilder().setName(folderResourceName).build();

      storageControl.deleteFolder(request);

      System.out.printf("Deleted folder: %s%n", folderResourceName);
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callDeleteFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  await controlClient.deleteFolder(request);
  console.log(`Deleted folder: ${folderName}.`);
}

callDeleteFolder();

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 the Cloud Storage Python API reference documentation.

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

from google.cloud import storage_control_v2


def delete_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 the Cloud Storage Ruby API reference documentation.

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

def delete_folder bucket_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_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::DeleteFolderRequest.new name: folder_path

  storage_control.delete_folder request

  puts "Deleted folder: #{folder_name}"
end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Use cURL to call the JSON API with a DELETE Folder request:

    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 bucket that contains the folder you want to delete. For example, my-bucket.

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

Get the metadata of a folder

This section describes how to get the metadata of a folder.

Command line

To get the metadata of a folder, run the following command:

gcloud storage folders describe gs://BUCKET_NAME/FOLDER_NAME

Where:

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

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

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

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name, std::string const& folder_id) {
  auto const name = std::string{"projects/_/buckets/"} + bucket_name +
                    "/folders/" + folder_id;
  auto folder = client.GetFolder(name);
  if (!folder) throw std::move(folder).status();

  std::cout << "Got folder: " << folder->name() << "\n";
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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.
func getFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "folder-name"

	ctx := context.Background()
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		return fmt.Errorf("NewStorageControlClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	// 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)
	if err != nil {
		return fmt.Errorf("GetFolder(%q): %w", folderPath, err)
	}

	fmt.Fprintf(w, "got folder metadata: %+v", f)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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


import com.google.storage.control.v2.Folder;
import com.google.storage.control.v2.FolderName;
import com.google.storage.control.v2.GetFolderRequest;
import com.google.storage.control.v2.StorageControlClient;
import java.io.IOException;

public final class GetFolder {

  public static void getFolder(String bucketName, String folderName) throws IOException {
    // 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 (StorageControlClient storageControl = StorageControlClient.create()) {

      GetFolderRequest request =
          GetFolderRequest.newBuilder()
              // Set project to "_" to signify globally scoped bucket
              .setName(FolderName.format("_", bucketName, folderName))
              .build();

      Folder newFolder = storageControl.getFolder(request);

      System.out.printf("Got folder: %s%n", newFolder.getName());
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callGetFolder() {
  const folderPath = controlClient.folderPath('_', bucketName, folderName);

  // Create the request
  const request = {
    name: folderPath,
  };

  // Run request
  const [response] = await controlClient.getFolder(request);
  console.log(`Got folder: ${response.name}.`);
}

callGetFolder();

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set 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 the Cloud Storage Python API reference documentation.

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

from google.cloud import storage_control_v2


def get_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 the Cloud Storage Ruby API reference documentation.

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

def get_folder bucket_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_path project: "_", bucket: bucket_name, folder: folder_name

  request = Google::Cloud::Storage::Control::V2::GetFolderRequest.new name: folder_path

  response = storage_control.get_folder request

  puts "Got folder #{response.name}"
end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Use cURL to call the JSON API with a GET Folder 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 bucket that contains the folder whose metadata you want to retrieve. For example, my-bucket.

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

Manage access on a folder

This section describes how to manage access on your folder by setting Identity and Access Management (IAM) policies, so you can get fine-grained access control 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 a managed folder with the same name as your existing folder. For detailed instructions, see Create a managed folder.

  2. Set and manage Identity and Access Management (IAM) policies on the managed folder you 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