In this article, we will see how to get the list of all versions of the object from S3 those are present in AWS Resource.
Example
List out all the versions of test.zip from Bucket_1/testfolder of S3.
Problem Statement: Use boto3 library in Python to get list of all versions of the object from S3.
Approach/Algorithm to solve this problem
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: bucket_name is the required parameter.
Step 3: Create an AWS session using boto3 lib
Step 4: Create an AWS client for s3
Step 5: Now, list out all version of the object of the given bucket using the function list_object_versions and handle the exceptions, if any.
Step 6: The result of the above function is a dictionary and contains all the versions of the object in the given bucket.
Step 7: Return the list of all versions of the object.
Example Code
Use the following code get the list of all versions of the object from AWS S3 −
import boto3 from botocore.exceptions import ClientError def list_all_objects_version(bucket_name, prefix_name): session = boto3.session.Session() s3_client = session.client('s3') try: result = s3_client.list_object_versions(Bucket=bucket_name, Prefix=prefix_name) except ClientError as e: raise Exception("boto3 client error in list_all_objects_version function: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in list_all_objects_version function of s3 helper: " + e.__str__()) print(list_all_objects_version("Bucket_1","testfolder"))
Output
{'ResponseMetadata': {'RequestId': 'H4VAGM3YP6', 'HostId': ***********', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': ***************', 'x-amz-request-id': 'H4VAGM3YP6', 'date': 'Sat, 03 Apr 2021 08:04:08 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': False, 'KeyMarker': '', 'VersionIdMarker': '', 'Versions': [{'ETag': '"705e2e674b04ca71"', 'Size': 1773, 'StorageClass': 'STANDARD', 'Key': 'testfolder/test.zip', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 12, 18, 14, 13, 18, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928*******************************'}}], 'Name': 'Bucket_1', 'Prefix': 'testfolder', 'MaxKeys': 1000, 'EncodingType': 'url'}