How to create cloud storage bucket with Python | GCP

Google provides Cloud Client Libraries for accessing Cloud APIs programmatically, google-cloud-storage is the client library for accessing Cloud storage services. In this tutorial we will see, how to create create cloud storage bucket and list objects of bucket with Python.

Pre-requisite for executing below code is to have a service account with Storage Admin role, refer How to create service account in GCPto create service account and downloading the json key.

Install Cloud storage client library

pip install google-cloud-storage

Import modules and authenticate to Google Cloud with downloaded service account json keys

from import storage
import os

# Provide path for service accounts keys for authentication
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = r"C:\Users\****\Desktop\keys.json"

Instantiates a storage client and give any unique name for the bucket to be created

# Instantiates a client
storage_client = storage.Client()
my_bucket_name = "[my-bucket-name]" # Replace [my-bucket-name] with actual bucket name

Create new bucket

bucket = storage_client.create_bucket(my_bucket_name)
msg = f"Bucket with name {} has been created"

List contents of bucket

Upload few images or text files in the newly bucket from Cloud console, for this tutorial few images were uploaded in the newly create bucket.

object_generator = storage_client.list_blobs(my_bucket_name)
for i in object_generator:

Example Output:

<Blob: [my-bucket-name], flower.jpg, 1588604065075004>
<Blob: [my-bucket-name], mountains.jpg, 1588604070602145>
<Blob: [my-bucket-name], sample.jpg, 1588604081103677>