Storage Control Create Folder

Sample to create folder in Storage Control

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& 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";
}

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 StorageControlCreateFolderSample
{
    public Folder StorageControlCreateFolder(string bucketName = "your-unique-bucket-name",
        string folderName = "your_folder_name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        var request = new CreateFolderRequest
        {
            // Set project to "_" to signify globally scoped bucket
            Parent = BucketName.FormatProjectBucket("_", bucketName),
            FolderId = folderName
        };

        Folder folder = storageControl.CreateFolder(request);

        Console.WriteLine($"Folder {folderName} created in bucket {bucketName}");
        return folder;
    }
}

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"
)

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

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

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

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

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

What's next

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