Get Object Metadata
Get object metadata without downloading it
Components
- Credentials
- Bucket Name
- Object Name
- .NET
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json;
namespace HeadObject
{
class HeadObject
{
private static IAmazonS3 _s3Client;
private const string BUCKET_NAME = "<BUCKET_NAME>";
private const string OBJECT_NAME = "<OBJECT_NAME>";
static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
HeadObjectHelper().Wait();
}
private static async Task HeadObjectHelper()
{
try
{
// Create the request
GetObjectMetadataRequest request = new ()
{
BucketName = BUCKET_NAME,
Key = OBJECT_NAME
};
// Submit the request
GetObjectMetadataResponse response = await _s3Client.GetObjectMetadataAsync(request);
Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_client = boto3.client(
'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:
response = s3_client.head_object(Bucket="smaple-bucket", Key="sample-object")
except ClientError as err:
status = err.response["ResponseMetadata"]["HTTPStatusCode"]
errcode = err.response["Error"]["Code"]
if status == 404:
logging.warning("Missing object, %s", errcode)
elif status == 403:
logging.error("Access denied, %s", errcode)
else:
logging.exception("Error in request, %s", errcode)
else:
logging.info(response)
// Import required AWS SDK clients and commands for Node.js
const { S3Client, HeadObjectCommand } = 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 HeadObjectCommand({
Bucket: 'sample_bucket',
Key: 'file.png',
VersionId: 'versionId',
})
);
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/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// Deletes the specified object in the specified S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_head_object BUCKET_NAME OBJECT_NAME
func main() {
if len(os.Args) != 3 {
exitErrorf("Bucket and object name required\nUsage: %s bucket_name object_name",
os.Args[0])
}
bucket := os.Args[1]
obj := os.Args[2]
// 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>"),
})
input := &s3.HeadObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(obj),
}
result, err := svc.HeadObject(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return
}
fmt.Println(result)
}
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_head_object.go:
go run s3_head_object BUCKET_NAME OBJECT_NAME