Add boto3.s3 type stubs
Because boto3 is dynamic, VS Code often can’t infer all methods unless you install stubs.
pip install "boto3-stubs[s3]"when type s3, you will get a clean method list
Bucket name
- must be lowercase
- globally unique
Create bucket
Link: create_bucket - Boto3 1.42.45 documentation
s3.client.create_bucket(
Bucket = bucket_name,
CreateBucketConfiguration = {
"LocationConstraint": "us-west-1'|'us-west-2"}
)Check exist bucket s3.head_bucket
s3.head_bucket(Bucket=bucketname)- If success
- Return 200 and
dict
- Return 200 and
- If fails, raises
ClientError- 403 →
AccesssDenied - 404 →
NotFound
- 403 →
botocore.exceptions.ClientError: An error occurred (404) when calling the HeadBucket operation: Not Found
error message:
{
'Error':
{'Code': '404',
'Message': 'Not Found'
},
'ResponseMetadata': {
'RequestId': 'B6SBVMRMN7G1WYBX',
'HostId':'MRg...T5p1bFlyA=',
'HTTPStatusCode': 404,
'HTTPHeaders':
{'x-amz-request-id': 'B...BX',
'x-amz-id-2': 'MR=...=bFlyA=',
'content-type': 'application/xml',
'transfer-encoding': 'chunked',
'date': 'Tue, 10 Feb 2026 00:44:53 GMT',
'server': 'AmazonS3'},
'RetryAttempts': 0}
}
ClientError
When calling AWS through boto3 (e.g., S3 or DynamoDB), requests may fail or be rejected.
In many of those cases, boto3 raises a ClientError
from botocore.exceptions import ClientError
def check_bucket_exist(bucketname, region):
s3 = boto3.client("s3", region_name = region)
try:
s3.head_bucket(Bucket=bucketname)
return True
except ClientError as e:
code = e.response.get("Error", {}).get("Code")
if code == "404":
return False
if code == "403":
print(f"--- AccessDenied ----")Enable versioning
s3.put_bucket_versioning(
Bucket=bucket,
VersioningConfiguration={"Status": "Enabled"},
)