shiv455
shiv455

Reputation: 7764

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

Upvotes: 3

Views: 9122

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269191

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])

Upvotes: 5

Related Questions