List Bucket's Objects
Components
- Bucket Name
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace ListObjectsExample
{
using System;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
public class ListObjects
{
private static IAmazonS3 _s3Client;
public static async Task Main()
{
string bucketName = "<BUCKET_NAME>";
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
Console.WriteLine($"Listing objects stored in the bucket {bucketName}.");
await ListingObjectsAsync(_s3Client, bucketName);
}
/// <summary>
/// Uses the client object to get a list of the objects in the S3
/// bucket in the bucketName parameter.
/// </summary>
/// <param name="client">The initialized S3 client obect used to call
/// the ListObjectsAsync method.</param>
/// <param name="bucketName">The bucket name for which you want to
/// retrieve a list of objects.</param>
public static async Task ListingObjectsAsync(IAmazonS3 client, string bucketName)
{
try
{
ListObjectsRequest request = new()
{
BucketName = bucketName,
MaxKeys = 5,
};
do
{
ListObjectsResponse response = await client.ListObjectsAsync(request);
// Process the response.
response.S3Objects
.ForEach(obj => Console.WriteLine($"{obj.Key,-35}{obj.LastModified.ToShortDateString(),10}{obj.Size,10}"));
// If the response is truncated, set the marker to get the next
// set of keys.
if (response.IsTruncated)
{
request.Marker = response.NextMarker;
}
else
{
request = null;
}
} while (request != null);
}
catch (AmazonS3Exception ex)
{
Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
}
}
}
}
<?php
require('client.php');
$bucket = $config['sample_bucket'];
$objectsListResponse = $client->listObjects(['Bucket' => $bucket]);
$objects = $objectsListResponse['Contents'] ?? [];
foreach ($objects as $object) {
echo $object['Key'] . "\t" . $object['Size'] . "\t" . $object['LastModified'] . "\n";
}
import boto3
import logging
from botocore.exceptions import ClientError
# Configure logging
logging.basicConfig(level=logging.INFO)
try:
# S3 resource
s3_resource = boto3.resource(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
bucket_name = 'bucket_name'
bucket = s3_resource.Bucket(bucket_name)
for obj in bucket.objects.all():
logging.info(f"object_name: {obj.key}, last_modified: {obj.last_modified}")
except ClientError as e:
logging.error(e)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, ListObjectsCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const run = async () => {
try {
const response = await s3.send(
new ListObjectsCommand({
Bucket: 'sample_bucket',
})
);
console.log('Success', response);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Lists the items in the specified S3 Bucket
//
// Usage:
// go run s3_list_objects.go BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("Bucket name required\nUsage: %s bucket_name",
os.Args[0])
}
bucket := os.Args[1]
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Get the list of items
resp, err := svc.ListObjectsV2(&s3.ListObjectsV2Input{Bucket: aws.String(bucket)})
if err != nil {
exitErrorf("Unable to list items in bucket %q, %v", bucket, err)
}
for _, item := range resp.Contents {
fmt.Println("Name: ", *item.Key)
fmt.Println("Last modified:", *item.LastModified)
fmt.Println("Size: ", *item.Size)
fmt.Println("Storage class:", *item.StorageClass)
fmt.Println("")
}
fmt.Println("Found", len(resp.Contents), "items in bucket", bucket)
fmt.Println("")
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_delete_bucket_website.go:
go run s3_list_objects.go BUCKET_NAME