All Products
Search
Document Center

Object Storage Service:Determine whether a bucket exists (Python SDK V1)

Last Updated:Mar 20, 2026

Use the OSS Python SDK V1 to check whether a bucket exists and whether your credentials can access it.

Prerequisites

Before you begin, ensure that you have:

Check whether a bucket exists

The following example wraps get_bucket_info() in a helper function that returns True if the bucket exists and False if it does not.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Load access credentials from environment variables.
# Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Set the endpoint for the region where your bucket is located.
# Example: China (Hangzhou) uses https://oss-cn-hangzhou.aliyuncs.com
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Set the region ID. Required for V4 signatures.
region = "cn-hangzhou"

# Replace <your-bucket-name> with the actual bucket name.
bucket = oss2.Bucket(auth, endpoint, "<your-bucket-name>", region=region)


def does_bucket_exist(bucket):
    try:
        bucket.get_bucket_info()
    except oss2.exceptions.NoSuchBucket:
        return False
    except:
        raise
    return True


exists = does_bucket_exist(bucket)
if exists:
    print("Bucket exists.")
else:
    print("Bucket does not exist.")

How it works

get_bucket_info() requires the oss:GetBucketAcl permission and confirms two things: whether the bucket exists, and whether your credentials can access it.

  • If the bucket does not exist, OSS raises oss2.exceptions.NoSuchBucket, and the function returns False.

  • If your credentials lack permission, OSS raises a different exception, which propagates to the caller.

  • If the call succeeds, the function returns True.

Usage notes

  • The example uses the public endpoint for the China (Hangzhou) region. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For details, see Regions and endpoints.

  • To create an OSSClient instance using a custom domain name or Security Token Service (STS), see Initialization.

References

The complete sample code for this operation is available in the GitHub example.