How to use Boto3 to paginate through all objects of a S3 bucket present in AWS Glue

Problem Statement: Use boto3 library in Python to paginate through all objects of a S3 bucket from AWS Glue Data Catalog that is created in your account
Step 1: Import boto3 and botocore exceptions to handle exceptions.
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 the required parameter.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 last key from a previous response.
Step 2:
max_items, page_size and starting_token are the optional parameters for this function, while bucket_name is the required parameter.
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.
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.
page_size denotes the size of each page.
starting_token helps to paginate, and it uses last key from a previous response.
starting_token helps to paginate, and it uses last key 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 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 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_objects.
Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_objects.
Step 6: 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: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter.
Step 7: It returns the number of records based on max_size and page_size.
Step 7: It returns the number of records based on max_size and page_size.
Step 8: Handle the generic exception if something went wrong while paginating.
Step 8: Handle the generic exception if something went wrong while paginating.
Use the following code to paginate through all objects of a S3 bucket created in user account −
import boto3
from botocore.exceptions import ClientError

def paginate_through_all_objects_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')
   try:
   paginator = s3_client.get_paginator('list_objects')
      response = paginator.paginate(Bucket=bucket_name, PaginationConfig={
         'MaxItems':max_items,
         'PageSize':page_size,
         'StartingToken':starting_token}
      )
   return response
   except ClientError as e:
      raise Exception("boto3 client error in paginate_through_all_objects_s3_bucket: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in paginate_through_all_objects_s3_bucket: " + e.__str__())

#1st Run
a = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5)
print(*a)
#2nd Run
for items in a:
next_token = items['Contents'][max_items-1]['Key']
b = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5,next_token)
print(*b)
#1st Run
{'ResponseMetadata': {'RequestId': '5AE5VF7RK', 'HostId': **************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': **************', 'x-amz-request-id': '5AE5VF7RK', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': '',
'Contents': [{'Key': 'analytics-s3i/param.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"e6f6b8e02"', 'Size': 1554, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************0'}}, {'Key': 'analytics-s3i/params.json', 'LastModified': datetime.datetime(2021, 3, 10, 20, 10, 47, tzinfo=tzutc()), 'ETag': '"22a4bf70c1ed2612"', 'Size': 1756, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}

#2nd Run
{'ResponseMetadata': {'RequestId': '5AEAWX', 'HostId': 'Uc********************************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': *****************************', 'x-amz-request-id': '5AEAWX', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': 'analytics-s3i/params.json',
'Contents': [{'Key': 'analytics-s3i/template.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"3af411f"', 'Size': 21334, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}, {'Key': 'analytics-s3i2/param.json', 'LastModified': datetime.datetime(2020, 11, 20, 17, 32, 45, tzinfo=tzutc()), 'ETag': '"04c29cf86888f99"', 'Size': 1695, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}