Use ListBuckets with an Amazon SDK or command line tool - Amazon Simple Storage Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Use ListBuckets with an Amazon SDK or command line tool

The following code examples show how to use ListBuckets.

.NET
Amazon SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

namespace ListBucketsExample { using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example uses the AWS SDK for .NET to list the Amazon Simple Storage /// Service (Amazon S3) buckets belonging to the default account. /// </summary> public class ListBuckets { private static IAmazonS3 _s3Client; /// <summary> /// Get a list of the buckets owned by the default user. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <returns>The response from the ListingBuckets call that contains a /// list of the buckets owned by the default user.</returns> public static async Task<ListBucketsResponse> GetBuckets(IAmazonS3 client) { return await client.ListBucketsAsync(); } /// <summary> /// This method lists the name and creation date for the buckets in /// the passed List of S3 buckets. /// </summary> /// <param name="bucketList">A List of S3 bucket objects.</param> public static void DisplayBucketList(List<S3Bucket> bucketList) { bucketList .ForEach(b => Console.WriteLine($"Bucket name: {b.BucketName}, created on: {b.CreationDate}")); } public static async Task Main() { // The client uses the AWS Region of the default user. // If the Region where the buckets were created is different, // pass the Region to the client constructor. For example: // _s3Client = new AmazonS3Client(RegionEndpoint.USEast1); _s3Client = new AmazonS3Client(); var response = await GetBuckets(_s3Client); DisplayBucketList(response.Buckets); } } }
  • For API details, see ListBuckets in Amazon SDK for .NET API Reference.

C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

bool AwsDoc::S3::ListBuckets(const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); auto outcome = client.ListBuckets(); bool result = true; if (!outcome.IsSuccess()) { std::cerr << "Failed with error: " << outcome.GetError() << std::endl; result = false; } else { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto &&b: outcome.GetResult().GetBuckets()) { std::cout << b.GetName() << std::endl; } } return result; }
  • For API details, see ListBuckets in Amazon SDK for C++ API Reference.

CLI
Amazon CLI

The following command uses the list-buckets command to display the names of all your Amazon S3 buckets (across all regions):

aws s3api list-buckets --query "Buckets[].Name"

The query option filters the output of list-buckets down to only the bucket names.

For more information about buckets, see Working with Amazon S3 Buckets in the Amazon S3 Developer Guide.

  • For API details, see ListBuckets in Amazon CLI Command Reference.

Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // ListBuckets lists the buckets in the current account. func (basics BucketBasics) ListBuckets() ([]types.Bucket, error) { result, err := basics.S3Client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) var buckets []types.Bucket if err != nil { log.Printf("Couldn't list buckets for your account. Here's why: %v\n", err) } else { buckets = result.Buckets } return buckets, err }
  • For API details, see ListBuckets in Amazon SDK for Go API Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.Bucket; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListBuckets { public static void main(String[] args) { Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listAllBuckets(s3); } public static void listAllBuckets(S3Client s3) { ListBucketsResponse response = s3.listBuckets(); List<Bucket> bucketList = response.buckets(); for (Bucket bucket: bucketList) { System.out.println("Bucket name "+bucket.name()); } } }
  • For API details, see ListBuckets in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

List the buckets.

import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new ListBucketsCommand({}); try { const { Owner, Buckets } = await client.send(command); console.log( `${Owner.DisplayName} owns ${Buckets.length} bucket${ Buckets.length === 1 ? "" : "s" }:`, ); console.log(`${Buckets.map((b) => ` • ${b.Name}`).join("\n")}`); } catch (err) { console.error(err); } };
PowerShell
Tools for PowerShell

Example 1: This command returns all S3 buckets.

Get-S3Bucket

Example 2: This command returns bucket named "test-files"

Get-S3Bucket -BucketName test-files
  • For API details, see ListBuckets in Amazon Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name @staticmethod def list(s3_resource): """ Get the buckets in all Regions for the current account. :param s3_resource: A Boto3 S3 resource. This is a high-level resource in Boto3 that contains collections and factory methods to create other high-level S3 sub-resources. :return: The list of buckets. """ try: buckets = list(s3_resource.buckets.all()) logger.info("Got buckets: %s.", buckets) except ClientError: logger.exception("Couldn't get buckets.") raise else: return buckets
  • For API details, see ListBuckets in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

require "aws-sdk-s3" # Wraps Amazon S3 resource actions. class BucketListWrapper attr_reader :s3_resource # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource. def initialize(s3_resource) @s3_resource = s3_resource end # Lists buckets for the current account. # # @param count [Integer] The maximum number of buckets to list. def list_buckets(count) puts "Found these buckets:" @s3_resource.buckets.each do |bucket| puts "\t#{bucket.name}" count -= 1 break if count.zero? end true rescue Aws::Errors::ServiceError => e puts "Couldn't list buckets. Here's why: #{e.message}" false end end # Example usage: def run_demo wrapper = BucketListWrapper.new(Aws::S3::Resource.new) wrapper.list_buckets(25) end run_demo if $PROGRAM_NAME == __FILE__
  • For API details, see ListBuckets in Amazon SDK for Ruby API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

async fn show_buckets(strict: bool, client: &Client, region: &str) -> Result<(), Error> { let resp = client.list_buckets().send().await?; let buckets = resp.buckets(); let num_buckets = buckets.len(); let mut in_region = 0; for bucket in buckets { if strict { let r = client .get_bucket_location() .bucket(bucket.name().unwrap_or_default()) .send() .await?; if r.location_constraint().unwrap().as_ref() == region { println!("{}", bucket.name().unwrap_or_default()); in_region += 1; } } else { println!("{}", bucket.name().unwrap_or_default()); } } println!(); if strict { println!( "Found {} buckets in the {} region out of a total of {} buckets.", in_region, region, num_buckets ); } else { println!("Found {} buckets in all regions.", num_buckets); } Ok(()) }
  • For API details, see ListBuckets in Amazon SDK for Rust API reference.

Swift
SDK for Swift
Note

This is prerelease documentation for an SDK in preview release. It is subject to change.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

/// Return an array containing information about every available bucket. /// /// - Returns: An array of ``S3ClientTypes.Bucket`` objects describing /// each bucket. public func getAllBuckets() async throws -> [S3ClientTypes.Bucket] { let output = try await client.listBuckets(input: ListBucketsInput()) guard let buckets = output.buckets else { return [] } return buckets }
  • For API details, see ListBuckets in Amazon SDK for Swift API reference.

For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.