Storage Control Create a Managed Folder

Storage Control Create a Managed Folder

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

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 a local development environment.

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

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

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 a local development environment.

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlCreateManagedFolderSample
{
    public ManagedFolder StorageControlCreateManagedFolder(string bucketId = "your-unique-bucket-name",
        string managedFolderId = "your_managed_folder_id")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        ManagedFolder managedFolder = storageControl.CreateManagedFolder(
            // Set project to "_" to signify globally scoped bucket
            new BucketName("_", bucketId),
            new ManagedFolder(),
            managedFolderId
        );

        Console.WriteLine($"Managed Folder {managedFolderId} created in bucket {bucketId}");
        return managedFolder;
    }
}

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 a local development environment.

import (
	"context"
	"fmt"
	"io"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	"cloud.google.com/go/storage/control/apiv2/controlpb"
)

// createManagedFolder creates a managed folder in the bucket with the given name.
func createManagedFolder(w io.Writer, bucket, folder string) error {
	// bucket := "bucket-name"
	// folder := "managed-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()
	mf := &controlpb.ManagedFolder{}

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

	fmt.Fprintf(w, "created Managed 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 a local development environment.


import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.CreateManagedFolderRequest;
import com.google.storage.control.v2.ManagedFolder;
import com.google.storage.control.v2.StorageControlClient;

public class CreateManagedFolder {
  public static void managedFolderCreate(String bucketName, String managedFolderId)
      throws Exception {

    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      CreateManagedFolderRequest request =
          CreateManagedFolderRequest.newBuilder()
              // Set project to "_" to signify global bucket
              .setParent(BucketName.format("_", bucketName))
              .setManagedFolder(ManagedFolder.newBuilder().build())
              .setManagedFolderId(managedFolderId)
              .build();
      String response = storageControlClient.createManagedFolder(request).getName();
      System.out.printf("Performed createManagedFolder request for %s%n", response);
    }
  }
}

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 a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// The name of your GCS bucket
// const bucketName = 'bucketName';

// The name of the managed folder to be created
// const managedFolderName = 'managedFolderName';

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

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

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

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

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

callCreateManagedFolder();

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 a local development environment.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\CreateManagedFolderRequest;
use Google\Cloud\Storage\Control\V2\ManagedFolder;

/**
 * Create a new folder in an existing bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $managedFolderId The name of your folder inside the bucket.
 *        (e.g. 'my-folder')
 */
function managed_folder_create(string $bucketName, string $managedFolderId): void
{
    $storageControlClient = new StorageControlClient();

    // Set project to "_" to signify global bucket
    $formattedName = $storageControlClient->bucketName('_', $bucketName);

    // $request = new CreateManagedFolderRequest([
    //     'parent' => $formattedName,
    //     'managedFolder' => new ManagedFolder(),
    //     'managedFolderId' => $managedFolderId,
    // ]);
    $request = CreateManagedFolderRequest::build($formattedName, new ManagedFolder(), $managedFolderId);

    $managedFolder = $storageControlClient->createManagedFolder($request);

    printf('Performed createManagedFolder request for %s', $managedFolder->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 a local development environment.

from google.cloud import storage_control_v2


def create_managed_folder(bucket_name: str, managed_folder_id: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    # The name of the managed folder to be created
    # managed_folder_id = "managed-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.CreateManagedFolderRequest(
        parent=bucket_path,
        managed_folder_id=managed_folder_id,
    )
    response = storage_control_client.create_managed_folder(request=request)

    print(f"Created managed 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 a local development environment.

def create_managed_folder bucket_name:, managed_folder_id:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of the managed folder to be created
  # managed_folder_id = "managed-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::CreateManagedFolderRequest.new parent: bucket_path,
                                                                                managed_folder_id: managed_folder_id

  response = storage_control.create_managed_folder request

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.