How to use Boto3 and AWS Client to determine whether a root bucket exists in S3?

Boto3PythonServer Side ProgrammingProgramming

Problem Statement − Use Boto3 library in Python to determine whether a root bucket exists in S3 or not.

Example − Bucket_1 exists or not in S3.

Approach/Algorithm to solve this problem

Step 1 − Import boto3 and botocore exceptions to handle exceptions.

Step 2 − Create an AWS session using boto3 library.

Step 3 − Create an AWS client for S3.

Step 4 − Use the function head_bucket(). It returns 200 OK if the bucket exists and the user has permission to access it. Otherwise, the response would be 403 Forbidden or 404 Not Found.

Step 5 − Handle the exception based on the response code.

Step 6 − Return True/False based on whether the bucket exists or not.


The following code checks whether the root bucket exists in S3 −

import boto3
from botocore.exceptions import ClientError

# To check whether root bucket exists or not
def bucket_exists(bucket_name):
      session = boto3.session.Session()
      # User can pass customized access key, secret_key and token as well
      s3_client = session.client('s3')
      print("Bucket exists.", bucket_name)
      exists = True
   except ClientError as error:
      error_code = int(error.response['Error']['Code'])
      if error_code == 403:
         print("Private Bucket. Forbidden Access! ", bucket_name)
      elif error_code == 404:
         print("Bucket Does Not Exist!", bucket_name)
      exists = False
   return exists



Bucket exists. bucket_1
Bucket Does Not Exist! AWS_bucket_1
Published on 22-Mar-2021 07:33:51