All Products
Search
Document Center

Object Storage Service:Get started

Last Updated:May 22, 2025

This topic describes how to use Object Storage Service (OSS) SDK for Python 2.0 to perform common operations. You can learn how to install OSS SDK for Python 2.0, configure access credentials, and perform basic operations, such as creating buckets and uploading, downloading, listing, and deleting objects.

Usage notes

  • For more information about the regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For information about how to configure access credentials for OSS SDK for Python 2.0, see Configure access credentials.

  • To use OSS SDK for Python 2.0 to initiate a request, you must first initialize an OSSClient instance. In this example, an OSSClient instance is created by using the default configurations. For information about how to configure an OSSClient instance for OSS SDK for Python 2.0, see Configure an OSSClient instance.

Prerequisites

Configure environment variables

  1. Create an AccessKey pair for a Resource Access Management (RAM) user that has full OSS access permissions.

    Create an AccessKey pair by using ROS

    You can quickly create an AccessKey pair for a RAM user that has full OSS access permissions by using a Resource Orchestration Service (ROS) script. To do so, go to the wizard for template-based stack creation, select I confirm that Alibaba Cloud ROS may create RAM resources in the Security Confirmation section, and click Create.

    1.png

    After the AccessKey pair is created, copy the AccessKey pair on the Outputs tab.

    image

  2. Configure environment variables for the AccessKey pair.

    Linux

    1. Run the following commands on the CLI to add the configurations of the environment variables to the ~/.bashrc file:

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Run the following command to apply the changes:

        source ~/.bashrc
      2. Run the following commands to check whether the environment variables have taken effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Run the following command in the terminal to view the default shell type:

      echo $SHELL
    2. Configure environment variables based on the default shell type.

      Zsh

      1. Run the following commands to add the configurations of the environment variables to the ~/.zshrc file:

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Run the following command to apply the changes:

        source ~/.zshrc
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Run the following commands to add the configurations of the environment variables to the ~/.bash_profile file:

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Run the following command to apply the changes:

        source ~/.bash_profile
      3. Run the following commands to check whether the environment variables take effect:

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Run the following commands in CMD:

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Run the following commands to check whether the environment variables take effect:

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Run the following commands in PowerShell:

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Run the following commands to check whether the environment variable takes effect:

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  3. After configuring the environment variables as described above, please restart or refresh your compilation and runtime environment, namely IDEs, command-line interfaces, other desktop applications, and background services, to ensure that the latest system environment variables are successfully loaded. 

Install OSS SDK for Python 2.0

  • Go to the Python official website and download and install the runtime environment of Python 3.8 or later. Run the following command to check whether Python is installed:

    Python --version
  • Run the following command to install OSS SDK for Python (preview version):

    Note

    Select an appropriate version of OSS SDK for Python based on your requirements. We recommend that you use the latest version to ensure that the code in this topic can run as expected.

    pip install alibabacloud-oss-v2
  • Run the following command to import the OSS SDK for Python package:

    import alibabacloud_oss_v2 as oss

Demo projects

The following examples describe how to create a bucket and upload, download, list, and delete objects.

Create a bucket

import argparse
import alibabacloud_oss_v2 as oss # Import OSS SDK for Python 2.0.

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="put bucket sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Execute the request to create a bucket, and set the bucket access control list (ACL) to private and the storage class to Standard.
    result = client.put_bucket(oss.PutBucketRequest(
        bucket=args.bucket,
        acl='private',
        create_bucket_configuration=oss.CreateBucketConfiguration(
            storage_class='Standard'
        )
    ))
    # Display the HTTP status code in the response and the request ID to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )


if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Upload an object

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Specify the data content that you want to upload.
    data = b'hello world'

    # Execute the request to upload an object, and specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
    ))

    # Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Download an object

import argparse
import alibabacloud_oss_v2 as oss
import os

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="get object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command line parameters.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Execute the request to download the object, and specify the bucket name and object name.
    result = client.get_object(oss.GetObjectRequest(
        bucket=args.bucket,  # Specify the name of the bucket.
        key=args.key, # Specify the name of the object.
    ))

    # Display the response to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' content range: {result.content_range},'
          f' content type: {result.content_type},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' content md5: {result.content_md5},'
          f' cache control: {result.cache_control},'
          f' content disposition: {result.content_disposition},'
          f' content encoding: {result.content_encoding},'
          f' expires: {result.expires},'
          f' hash crc64: {result.hash_crc64},'
          f' storage class: {result.storage_class},'
          f' object type: {result.object_type},'
          f' version id: {result.version_id},'
          f' tagging count: {result.tagging_count},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' next append position: {result.next_append_position},'
          f' expiration: {result.expiration},'
          f' restore: {result.restore},'
          f' process status: {result.process_status},'
          f' delete marker: {result.delete_marker},'
    )

    with result.body as body_stream:
        data = body_stream.read()
        print(f "The object is read. Data length: {len(data)} bytes")

        path = "./get-object-sample.txt"
        with open(path, 'wb') as f:
            f.write(data)
        print(f "The object is downloaded and saved to a local path: {path}")

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

List objects

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="list objects v2 sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Create a paginator to allow the ListObjectsV2 operation to list objects.
    paginator = client.list_objects_v2_paginator()

    # Traverse each page in the paginator.
    for page in paginator.iter_page(oss.ListObjectsV2Request(
            bucket=args.bucket
        )
    ):
        # Traverse objects on each page.
        for o in page.contents:
            # Display the name, size, and last modified time of the object.
            print(f'Object: {o.key}, {o.size}, {o.last_modified}')

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Delete an object

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser.
parser = argparse.ArgumentParser(description="delete object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line parameters.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint that other services can use to access OSS.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Execute the request to delete the object, and specify the bucket name and object name.
    result = client.delete_object(oss.DeleteObjectRequest(
        bucket=args.bucket,
        key=args.key,
    ))

    # Display the HTTP status code in the response, the request ID, and the version ID and the delete marker of the object to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' delete marker: {result.delete_marker},'
    )

if __name__ == "__main__":
    main() # Specify the entry points in the main function of the script when the script is directly run.

Example

  1. Create the main.py file in the directory of your demo project. Copy the preceding sample code to the main.py file based on your business requirements.

  2. Replace "your region", "your bucket name", and "your object key" in the following command with your actual configurations. Replace "your region" with the region in which your bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.

    python main.py --region "your region" --bucket "your bucket name" --key "your object key"

FAQ

What do I do if the AccessDenied error is reported when using OSS SDKs?

The AccessDenied error typically occurs due to insufficient access permissions. Below are steps to resolve this issue:

  1. Verify AccessKey ID and AccessKey Secret: Please make sure that the AccessKey ID and AccessKey Secret you use are correct. For more information, see Create an AccessKey pair.

  2. Check the permissions granted to RAM users: Please make sure that the RAM user has permissions required to perform operations on the bucket or the object. For more information, see Grant permissions to a RAM user.

  3. Check bucket policies: If the error message contains 'Access denied by bucket policy,' it indicates that the error occured due to restrictions specified in the bucket policies. For more information, see Bucket policies.

  4. For information about other types of errors, see Error codes. For example, you can refer to the 03-ACCESS_CONTROL section for common errors related to access control.

References