How to use Boto3 to paginate through object versions of a S3 bucket present in AWS Glue

Problem Statement: Use boto3 library in Python to paginate through object versions of a S3 bucket from AWS Glue Data Catalog that is created in your account

Approach/Algorithm to solve this problem

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: max_items, page_size and starting_token are the optional parameters for this function, while bucket_name is required parameters.

    • max_items denote the total number of records to return. If the number of available records > max_items then a NextToken will be provided in the response to resume pagination.

    • page_size denotes the size of each page.

    • starting_token helps to paginate, and it uses NextKeyMarker from a previous response.

  • Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.

  • Step 4: Create an AWS client for S3.

  • Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_object_versions.

  • Step 5: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter.

  • Step 6: It returns the number of records based on max_size and page_size.

  • Step 7: Handle the generic exception if something went wrong while paginating.

Example Code

Use the following code to paginate through object versions of a S3 bucket created in user account −

import boto3
from botocore.exceptions import ClientError

def paginate_through_object_version_s3_bucket(bucket_name, max_items=None:int,page_size=None:int, starting_token=None:string):
   session = boto3.session.Session()
   s3_client = session.client('s3')
   paginator = s3_client.get_paginator('list_object_versions')
      response = paginator.paginate(Bucket=bucket_name, PaginationConfig={
   return response
   except ClientError as e:
      raise Exception("boto3 client error in paginate_through_object_version_s3_bucket: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in paginate_through_object_version_s3_bucket: " + e.__str__())

#1st Run
a = paginate_through_object_version_s3_bucket('s3-test-bucket',2,5)
#2nd Run
for items in a:
next_token = (items['NextKeyMarker'])
b = paginate_through_object_version_s3_bucket('s3-test-bucket',2,5,next_token)


#1st Run
{'ResponseMetadata': {'RequestId': 'XEVY**************CD0', 'HostId': **************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': *******************', 'x-amz-request-id': 'XEVYV***************', 'date': 'Sat, 03 Apr 2021 07:14:49 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'KeyMarker': '', 'VersionIdMarker': '', 'NextKeyMarker': 'analytics-s3/template.json', 'NextVersionIdMarker': 'null',
'Versions': [{'ETag': '"e66659e02"', 'Size': 1554, 'StorageClass': 'STANDARD', 'Key': 'analytics-s3i/param.json', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928b5bd**************3d70'}},
{'ETag': '"22a4bf7**************9c1ed2612"', 'Size': 1756, 'StorageClass': 'STANDARD', 'Key': 'analytics-s3i/params.json', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2021, 3, 10, 20, 10, 47, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '928b5bde*****************2d4423d70'}}],
'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'DeleteMarkers': None, 'CommonPrefixes': None}

#2nd Run
{'ResponseMetadata': {'RequestId': '3V9*********703V', 'HostId': ****************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': '************************', 'x-amz-request-id': '3V9****************V', 'date': 'Sat, 03 Apr 2021 07:18:56 GMT', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0},
'IsTruncated': True, 'KeyMarker': analytics-s3i2/template.json', 'VersionIdMarker': '', 'NextKeyMarker': 'analytics-s3l/params.json', 'NextVersionIdMarker': 'null', 'Versions':
[{'ETag': '"dbd336ff00cb5af3d"', 'Size': 1557, 'StorageClass': 'STANDARD', 'Key': 'analytics-s3i3/param.json', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 10, 28, 18, 16, 38, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '*****************'}},
{'ETag': '"66b49598df6"', 'Size': 21334, 'StorageClass': 'STANDARD', 'Key': 'analytics-s3i3/template.json', 'VersionId': 'null', 'IsLatest': True, 'LastModified': datetime.datetime(2020, 10, 28, 18, 16, 38, tzinfo=tzutc()), 'Owner': {'DisplayName': 'AWS.Development', 'ID': '****************'}}],
'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'DeleteMarkers': None, 'CommonPrefixes': None}

Updated on: 15-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started