IBM Cloud Object Storage SDK for Python

2.16.1 · active · verified Sat Apr 11

The IBM Cloud Object Storage SDK for Python (ibm-cos-sdk) is a Python package allowing developers to interact with IBM Cloud Object Storage. It is a fork of the popular boto3 library, adapted for IBM Cloud's IAM authentication, and provides an S3-compatible API. The library is actively maintained with frequent updates, currently at version 2.16.1, adding features like S3 Object Lock Governance Mode and Checksums Support.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to IBM Cloud Object Storage, list existing buckets, and perform basic file upload and download operations. It uses environment variables for secure credential handling. Ensure you replace placeholder values or set corresponding environment variables with your IBM Cloud API Key, resource instance ID, IAM authentication endpoint, and service endpoint.

import os
import ibm_boto3
from ibm_botocore.client import Config

# --- Environment Variables (Replace with your actual credentials/endpoints) ---
# Get these values from your IBM Cloud Object Storage service credentials.
# Set them as environment variables or replace directly in code (not recommended for production).
API_KEY = os.environ.get('IBM_COS_API_KEY_ID', 'YOUR_API_KEY_ID')
SERVICE_INSTANCE_ID = os.environ.get('IBM_COS_RESOURCE_INSTANCE_ID', 'YOUR_SERVICE_INSTANCE_ID')
AUTH_ENDPOINT = os.environ.get('IBM_COS_AUTH_ENDPOINT', 'https://iam.cloud.ibm.com/identity/token') # e.g., 'https://iam.cloud.ibm.com/identity/token'
SERVICE_ENDPOINT = os.environ.get('IBM_COS_ENDPOINT', 'https://s3.us.cloud-object-storage.appdomain.cloud') # e.g., 'https://s3.us.cloud-object-storage.appdomain.cloud'

if not all([API_KEY, SERVICE_INSTANCE_ID, AUTH_ENDPOINT, SERVICE_ENDPOINT]):
    print("Error: Missing one or more required environment variables for IBM COS configuration.")
    print("Please set IBM_COS_API_KEY_ID, IBM_COS_RESOURCE_INSTANCE_ID, IBM_COS_AUTH_ENDPOINT, IBM_COS_ENDPOINT.")
    exit(1)

try:
    # Create client object
    cos_client = ibm_boto3.client(
        's3',
        ibm_api_key_id=API_KEY,
        ibm_service_instance_id=SERVICE_INSTANCE_ID,
        ibm_auth_endpoint=AUTH_ENDPOINT,
        config=Config(signature_version='oauth'),
        endpoint_url=SERVICE_ENDPOINT
    )

    print("Successfully connected to IBM Cloud Object Storage. Listing buckets...")

    # List buckets
    response = cos_client.list_buckets()
    for bucket in response['Buckets']:
        print(f"Bucket Name: {bucket['Name']}")

    # Example: Upload a simple text file
    bucket_name = "my-test-bucket-12345" # Replace with an existing bucket or create a new one
    object_name = "hello_cos.txt"
    data = "Hello from IBM COS Python SDK!"
    try:
        cos_client.put_object(Bucket=bucket_name, Key=object_name, Body=data)
        print(f"Successfully uploaded '{object_name}' to bucket '{bucket_name}'.")

        # Example: Download the file
        obj = cos_client.get_object(Bucket=bucket_name, Key=object_name)
        downloaded_data = obj['Body'].read().decode('utf-8')
        print(f"Downloaded '{object_name}': {downloaded_data}")

    except cos_client.exceptions.NoSuchBucket:
        print(f"Warning: Bucket '{bucket_name}' not found. Skipping upload/download examples.")
    except Exception as e:
        print(f"An error occurred during object operations: {e}")

except Exception as e:
    print(f"Failed to connect to IBM Cloud Object Storage: {e}")

view raw JSON →