Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boto3 version of list-objects-v2 --query command in AWS CLI

Would like to know the python boto3 code for below AWS CLI

aws s3api list-objects-v2 \
--bucket myBucket \
--prefix path1/path2 \
--query 'reverse(sort_by(Contents,&LastModified))[0]'

i didnt see any query option for list_objects_v2

https://boto3.readthedocs.io/en/stable/reference/services/s3.html#S3.Client.list_objects_v2

like image 974
shiv455 Avatar asked May 06 '26 21:05

shiv455


1 Answers

The --query capability in the AWS Command-Line Interface (CLI) is a feature of the CLI itself, rather than being performed during an API call.

If you are using the boto3 list_object_v2() command, a full set of results is returned.

You can then use Python to manipulate the results.

It appears that you are wanting to list the most recent object in the bucket/path, so you could use something like:

import boto3

client = boto3.client('s3',region_name='ap-southeast-2')

response = client.list_objects_v2(Bucket='my-bucket')

print (sorted(response['Contents'], key=lambda item: item['LastModified'])[-1])
like image 56
John Rotenstein Avatar answered May 08 '26 12:05

John Rotenstein