How to retrieve AWS S3 objects URL using python

Viewed 118

I need to write a lambda function that retrieves s3 object URL for object preview. I came across this solution, but I have a question about it. In my case, I would like to retrieve URL of any object in my s3 bucket, hence there is no Keyname.How can i retriece url of any future objects stored in my s3 bucket.

bucket_name = 'aaa'
aws_region = boto3.session.Session().region_name
object_key = 'aaa.png'

s3_url = f"https://{bucket_name}.s3.{aws_region}.amazonaws.com/{object_key}"

return {
   'statusCode': 200,
   'body': json.dumps({'s3_url': s3_url})
}
1 Answers

You have some examples here. But, what exactly would you like to do? What do you mean by future objects? You can put a creation event on your bucket that will trigger your lambda each time when a new object is uploaded into that bucket.

import boto3

def lambda_handler(event, context):
    print(event)
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    s3 = boto3.client('s3')
    obj = s3.get_object(
        Bucket=bucket,
        Key=key
    )
    print(obj['Body'].read().decode('utf-8'))
Related