Listing buckets

This page shows you how to list the Cloud Storage buckets in a project, which are ordered in the list lexicographically by name. For an overview of buckets, read the Key Terms.

Prerequisites

Prerequisites can vary based on the tool used:

Console

In order to complete this guide using the Google Cloud console, you must have the proper IAM permissions. If you did not create the project you want to access, you might need the project owner to give you a role that contains the necessary permissions.

For a list of permissions required for specific actions, see IAM permissions for the Google Cloud console.

For a list of relevant roles, see Cloud Storage roles. Alternatively, you can create a custom role that has specific, limited permissions.

Command line

In order to complete this guide using a command-line utility, you must have the proper IAM permissions. If you did not create the project you want to access, you might need the project owner to give you a role that contains the necessary permissions.

For a list of permissions required for specific actions, see IAM permissions for gsutil commands.

For a list of relevant roles, see Cloud Storage roles. Alternatively, you can create a custom role that has specific, limited permissions.

Code samples

In order to complete this guide using the Cloud Storage client libraries, you must have the proper IAM permissions. If you did not create the project you want to access, you might need the project owner to give you a role that contains the necessary permissions. Unless otherwise noted, client library requests are made through the JSON API.

For a list of permissions required for specific actions, see IAM permissions for JSON methods.

For a list of relevant roles, see Cloud Storage roles. Alternatively, you can create a custom role that has specific, limited permissions.

REST APIs

JSON API

In order to complete this guide using the JSON API, you must have the proper IAM permissions. If you did not create the project you want to access, you might need the project owner to give you a role that contains the necessary permissions.

For a list of permissions required for specific actions, see IAM permissions for JSON methods.

For a list of relevant roles, see Cloud Storage roles. Alternatively, you can create a custom role that has specific, limited permissions.

List the buckets in a project

Console

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

    Go to Browser

Buckets that are part of the currently selected project appear in the browser list.

Optionally, use filtering to narrow the results in your list.

Command line

gcloud

Use the gcloud alpha storage ls command:

gcloud alpha storage ls

The response looks like the following example:

gs://BUCKET_NAME1/
gs://BUCKET_NAME2/
gs://BUCKET_NAME3/
...

gsutil

Use the gsutil ls command:

gsutil ls

The response looks like the following example:

gs://BUCKET_NAME1/
gs://BUCKET_NAME2/
gs://BUCKET_NAME3/
...

Code samples

C++

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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
  int count = 0;
  gcs::ListBucketsReader bucket_list = client.ListBuckets();
  for (auto&& bucket_metadata : bucket_list) {
    if (!bucket_metadata) {
      throw std::runtime_error(bucket_metadata.status().message());
    }

    std::cout << bucket_metadata->name() << "\n";
    ++count;
  }

  if (count == 0) {
    std::cout << "No buckets in default project\n";
  }
}

C#

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


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class ListBucketsSample
{
    public IEnumerable<Bucket> ListBuckets(string projectId = "your-project-id")
    {
        var storage = StorageClient.Create();
        var buckets = storage.ListBuckets(projectId);
        Console.WriteLine("Buckets:");
        foreach (var bucket in buckets)
        {
            Console.WriteLine(bucket.Name);
        }
        return buckets;
    }
}

Go

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

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

	"cloud.google.com/go/storage"
	"google.golang.org/api/iterator"
)

// listBuckets lists buckets in the project.
func listBuckets(w io.Writer, projectID string) ([]string, error) {
	// projectID := "my-project-id"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

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

	var buckets []string
	it := client.Buckets(ctx, projectID)
	for {
		battrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		buckets = append(buckets, battrs.Name)
		fmt.Fprintf(w, "Bucket: %v\n", battrs.Name)
	}
	return buckets, nil
}

Java

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

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListBuckets {
  public static void listBuckets(String projectId) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Page<Bucket> buckets = storage.list();

    for (Bucket bucket : buckets.iterateAll()) {
      System.out.println(bucket.getName());
    }
  }
}

Node.js

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

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function listBuckets() {
  const [buckets] = await storage.getBuckets();

  console.log('Buckets:');
  buckets.forEach(bucket => {
    console.log(bucket.name);
  });
}

listBuckets().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * List all Cloud Storage buckets for the current project.
 */
function list_buckets()
{
    $storage = new StorageClient();
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

Python

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

from google.cloud import storage


def list_buckets():
    """Lists all buckets."""

    storage_client = storage.Client()
    buckets = storage_client.list_buckets()

    for bucket in buckets:
        print(bucket.name)

Ruby

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

def list_buckets
  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  storage.buckets.each do |bucket|
    puts bucket.name
  end
end

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication.
  2. Use cURL to call the JSON API with a GET Service request:

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • PROJECT_IDENTIFIER is the ID or number of the project containing the buckets you want to list. For example, my-project.

    You can use a prefix=PREFIX query string parameter to limit results to buckets that have the specified prefix.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials. For instructions, see API authentication.
  2. Use cURL to call the XML API with a GET Service request:

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.googleapis.com"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • PROJECT_ID is the ID of the project containing the buckets you want to list. For example, my-project.

    You can use a prefix=PREFIX query string parameter to limit results to buckets that have the specified prefix.

What's next