List bucket labels

Retrieve the labels for a Cloud Storage bucket.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name, gcs::Fields("labels"));

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  if (bucket_metadata->labels().empty()) {
    std::cout << "The bucket " << bucket_name << " has no labels set.\n";
    return;
  }

  std::cout << "The labels for bucket " << bucket_name << " are:";
  for (auto const& kv : bucket_metadata->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Prints a list of a bucket's lables.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_bucket_labels($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();
    if (isset($info['labels'])) {
        foreach ($info['labels'] as $labelKey => $labelValue) {
            printf('%s: %s' . PHP_EOL, $labelKey, $labelValue);
        }
    }
}

Python

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

import pprint

from google.cloud import storage


def get_bucket_labels(bucket_name):
    """Prints out a bucket's labels."""
    # bucket_name = 'your-bucket-name'
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)

    labels = bucket.labels
    pprint.pprint(labels)

What's next

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