Delete an empty Amazon S3 bucket using an Amazon SDK - 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.

Delete an empty Amazon S3 bucket using an Amazon SDK

The following code examples show how to delete an empty S3 bucket.

.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.

/// <summary> /// Shows how to delete an Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param> /// <returns>A boolean value that represents the success or failure of /// the delete operation.</returns> public static async Task<bool> DeleteBucketAsync(IAmazonS3 client, string bucketName) { var request = new DeleteBucketRequest { BucketName = bucketName, }; var response = await client.DeleteBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • For API details, see DeleteBucket 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::DeleteBucket(const Aws::String &bucketName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketOutcome outcome = client.DeleteBucket(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: DeleteBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "The bucket was deleted" << std::endl; } return outcome.IsSuccess(); }
  • For API details, see DeleteBucket in Amazon SDK for C++ API 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.

fmt.Println("Delete a bucket") // Delete the bucket. _, err = client.DeleteBucket(context.TODO(), &s3.DeleteBucketInput{ Bucket: aws.String(name), }) if err != nil { panic("Couldn't delete bucket: " + err.Error()) }
  • For API details, see DeleteBucket 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.

DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() .bucket(bucket) .build(); s3.deleteBucket(deleteBucketRequest); s3.close();
  • For API details, see DeleteBucket 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.

Create the client.

// Create service client module using ES6 syntax. import { S3Client } from "@aws-sdk/client-s3"; // Set the AWS Region. const REGION = "us-east-1"; // Create an Amazon S3 service client object. const s3Client = new S3Client({ region: REGION }); export { s3Client };

Delete the bucket.

// Import required AWS SDK clients and commands for Node.js. import { DeleteBucketCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Helper function that creates an Amazon S3 service client module. // Set the bucket parameters export const bucketParams = { Bucket: "BUCKET_NAME" }; export const run = async () => { try { const data = await s3Client.send(new DeleteBucketCommand(bucketParams)); return data; // For unit tests. console.log("Success - bucket deleted"); } catch (err) { console.log("Error", err); } }; // Invoke run() so these examples run out of the box. run();
PHP
SDK for PHP
Note

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

Delete an empty bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2', 'version' => 'latest']); try { $s3client->deleteBucket([ 'Bucket' => $bucket_name, ]); echo "Deleted bucket $bucket_name.\n"; } catch (Exception $exception) { echo "Failed to delete $bucket_name with error: " . $exception->getMessage(); exit("Please fix error with bucket deletion before continuing."); }
  • For API details, see DeleteBucket in Amazon SDK for PHP API 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 def delete(self): """ Delete the bucket. The bucket must be empty or an error is raised. """ try: self.bucket.delete() self.bucket.wait_until_not_exists() logger.info("Bucket %s successfully deleted.", self.bucket.name) except ClientError: logger.exception("Couldn't delete bucket %s.", self.bucket.name) raise
  • For API details, see DeleteBucket 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.

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase if answer == "y" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • For API details, see DeleteBucket in Amazon SDK for Ruby API Reference.

Rust
SDK for Rust
Note

This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.

Note

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

pub async fn delete_bucket(client: &Client, bucket_name: &str) -> Result<(), Error> { client.delete_bucket().bucket(bucket_name).send().await?; println!("Bucket deleted"); Ok(()) }
  • For API details, see DeleteBucket 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.

public func deleteBucket(name: String) async throws { let input = DeleteBucketInput( bucket: name ) _ = try await client.deleteBucket(input: input) }
  • For API details, see DeleteBucket 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.