Create a Google Cloud Storage Bucket using Python

Google Cloud Storage (GCS) is a scalable object storage service. In this tutorial, we will learn how to create a new storage bucket in your project using the google-cloud-storage Python library.

Install the Client Library

Bash

pip install google-cloud-storage    

This command installs the google-cloud-storage client library required to interact with Google Cloud Storage.

Python Code to Create Bucket

We will use the create_bucket() method of the storage.Client class.

Python

# Import required packages
from dotenv import load_dotenv
import os
from google.oauth2 import service_account
from google.cloud import storage

def main():
    # Load environment variables from .env file
    load_dotenv()

    # Read values from environment variables
    credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
    project_name = os.getenv("project_id")

    # Load service account credentials
    credentials = service_account.Credentials.from_service_account_file(
        credentials_path
    )

    # Create Storage client
    client = storage.Client(credentials=credentials, project=project_name)

    # Bucket name (must be globally unique)
    bucket_name = "new-bucket-via-python-sdk"

    # Create a new bucket with a specific location
    bucket = client.create_bucket(
        bucket_name,       # Bucket name
        location="us-east1"  # Regional location
    )

    print(f"Bucket {bucket.name} created successfully")

if __name__ == "__main__":
    main()    

Key Steps Explained

Note: Bucket names must be globally unique across all of Google Cloud, not just within your project.