Python – The boto3 version of the list-objects-v2 –query command in the AWS CLI

The boto3 version of the list-objects-v2 –query command in the AWS CLI… here is a solution to the problem.

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

Want to know the python boto3 code for the AWS CLI below

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

I don’t see any query options for list_objects_v2

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

Solution

The –query feature in AWS Command-Line Interface (CLI) is a feature of the CLI itself, not performed during API calls.

If you are using boto3 >list_ object_v2() command to return the full set of results.

You can then use Python to manipulate the results.

It seems that you want to list the latest objects in the bucket/path, so you can 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])

Related Problems and Solutions