All Products
Search
Document Center

Object Storage Service:Set object tags (Python SDK V1)

Last Updated:Nov 26, 2025

Object Storage Service (OSS) allows you to configure object tags to classify objects. You can configure lifecycle rules and control access to objects based on tags.

Usage notes

  • Before you configure object tagging, make sure that you are familiar with the feature. For more information, see Object tagging.

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see OSS regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To add a tag to an object, you must have the oss:PutObjectTagging permission. For more information, see Attach a custom policy to a RAM user.

Add tags when you upload an object

  • Add tags during a simple upload

    The following code shows how to add tags to an object during a simple upload.

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the tag information in the HTTP header.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Specify headers when you call the put_object operation to add tags to the uploaded object.
    result = bucket.put_object(object_name, 'content', headers=headers)
    print('http response status: ', result.status)
    
    # View the object tags.
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • Add tags during a multipart upload

    The following code shows how to add tags to an object during a multipart upload.

    # -*- coding: utf-8 -*-
    
    import os
    import oss2
    from oss2 import SizedFileAdapter, determine_part_size
    from oss2.models import PartInfo
    from oss2.headers import OSS_OBJECT_TAGGING
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    # Enter the full path of the local file. For example, enter D:\\localpath\\examplefile.txt.
    # If you specify only the file name, such as examplefile.txt, without a path, the file is uploaded from the local path of the project where the sample program is located.
    filename = 'D:\\localpath\\examplefile.txt'
    
    total_size = os.path.getsize(filename)
    # The determine_part_size method determines the part size.
    part_size = determine_part_size(total_size, preferred_size=100 * 1024)
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the tag information in the HTTP header.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Initialize the multipart upload.
    # Specify headers when you call the init_multipart_upload operation to add tags to the uploaded object.
    upload_id = bucket.init_multipart_upload(object_name, headers=headers).upload_id
    parts = []
    
    # Upload parts one by one.
    with open(filename, 'rb') as fileobj:
        part_number = 1
        offset = 0
        while offset < total_size:
            num_to_upload = min(part_size, total_size - offset)
            # The SizedFileAdapter(fileobj, size) method generates a new file object and recalculates the starting position for the append operation.
            result = bucket.upload_part(object_name, upload_id, part_number,
                                        SizedFileAdapter(fileobj, num_to_upload))
            parts.append(PartInfo(part_number, result.etag))
    
            offset += num_to_upload
            part_number += 1
    
    # Complete the multipart upload.
    result = bucket.complete_multipart_upload(object_name, upload_id, parts)
    print('http response status: ', result.status)
    
    # View the object tags.
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # Verify the multipart upload.
    with open(filename, 'rb') as fileobj:
        assert bucket.get_object(object_name).read() == fileobj.read()
  • Add tags during an append upload

    The following code shows how to add tags to an object during an append upload.

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the tag information in the HTTP header.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Append the object. Specify headers when you call the append_object operation to add tags to the object.
    # Only the tags set in the first call to append_object take effect. Tags added in subsequent append operations are ignored.
    result = bucket.append_object(object_name, 0, '<yourContent>', headers=headers)
    
    # View the object tags.
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • Add tags during a resumable upload

    The following code shows how to add tags to an object during a resumable upload.

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    # Enter the full path of the local file. If you do not specify a local path, the file is uploaded from the local path of the project where the sample program is located.
    local_file = 'D:\\localpath\\examplefile.txt'
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the tag information in the HTTP header.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Multipart upload is used when the file size is greater than or equal to the value of the optional multipart_threshold parameter. The default value is 10 MB. If you do not use the store parameter to specify a directory, a .py-oss-upload directory is created in the HOME directory to save checkpoint information.
    # Specify headers when you call the resumable_upload operation to add tags to the uploaded object.
    oss2.resumable_upload(bucket, object_name, local_file, headers=headers)
    
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))

Add or change tags for an existing object

If you did not add tags when you uploaded an object, or if the existing tags do not meet your requirements, you can add or change the tags after the object is uploaded.

The following code shows how to add or change tags for an existing object.

# -*- coding: utf-8 -*-

import oss2
from oss2.models import Tagging, TaggingRule
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Enter the bucket name.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'

# Create a tagging rule.
rule = TaggingRule()
rule.add('key1', 'value1')
rule.add('key2', 'value2')

# Create tags.
tagging = Tagging(rule)

# Set the tags.
result = bucket.put_object_tagging(object_name, tagging)
# View the HTTP status code.
print('http response status:', result.status)

Add or change tags for a specific object version

In a bucket with versioning enabled, you can add or change tags for a specific version of an object by specifying its version ID.

The following code shows how to add or change tags for a specific object version.

Note

For more information about how to obtain a version ID, see List objects (Python SDK V1).

# -*- coding: utf-8 -*-

import oss2
from oss2.models import Tagging
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Enter the bucket name.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Enter the full path of the object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'
# Enter the version ID of the object. For example, CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****.
version_id = 'CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****'

tagging = Tagging()
# Specify the key and value for each object tag. For example, set the key to owner and the value to John.
tagging.tag_set.add('owner', 'John')
tagging.tag_set.add('type', 'document')

params = dict()
params['versionId'] = version_id

bucket.put_object_tagging(object_name, tagging, params=params)

Set object tags when you copy an object

When you copy an object, you can specify how to set the tags for the destination object. The valid values are:

  • Copy (default): Copies the tags from the source object to the destination object.

  • Replace: Ignores the tags of the source object and applies the tags specified in the request to the destination object.

The following examples show how to set object tags when you copy an object. A simple copy is used for objects smaller than 1 GB, and a multipart copy is used for objects that are larger than 1 GB.

  • Set tags during a simple copy

    The following code shows how to set object tags when you copy an object that is smaller than 1 GB.

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING, OSS_OBJECT_TAGGING_COPY_DIRECTIVE
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the source object. The full path cannot include the bucket name. For example, enter srcexampledir/exampleobject.txt.
    src_object_name = 'srcexampledir/exampleobject.txt'
    # Enter the full path of the destination object. The full path cannot include the bucket name. For example, enter destexampledir1/exampleobject.txt.
    dest_object_name1 = 'destexampledir1/exampleobject.txt'
    # Enter the full path of the destination object. The full path cannot include the bucket name. For example, enter destexampledir2/exampleobject.txt.
    dest_object_name2 = 'destexampledir2/exampleobject.txt'
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the OSS_OBJECT_TAGGING_COPY_DIRECTIVE parameter in the HTTP header to COPY, or leave it unspecified. The destination object dest_object_name1 will then have the same tags as the source object.
    headers=dict()
    headers[OSS_OBJECT_TAGGING_COPY_DIRECTIVE] = 'COPY'
    bucket.copy_object(bucket.bucket_name, src_object_name, dest_object_name1, headers=headers)
    
    # Set the OSS_OBJECT_TAGGING_COPY_DIRECTIVE parameter in the HTTP header to REPLACE. The tags for the destination object dest_object_name2 are then set to the tags specified by headers[OSS_OBJECT_TAGGING].
    headers[OSS_OBJECT_TAGGING_COPY_DIRECTIVE] = 'REPLACE'
    headers[OSS_OBJECT_TAGGING] = tagging
    bucket.copy_object(bucket.bucket_name, src_object_name, dest_object_name2, headers=headers)
    
    # View the tags of src_object_name.
    result = bucket.get_object_tagging(src_object_name)
    for key in result.tag_set.tagging_rule:
        print('src tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags of dest_object_name1. The tags of dest_object_name1 are the same as the tags of src_object_name.
    result = bucket.get_object_tagging(dest_object_name1)
    for key in result.tag_set.tagging_rule:
        print('dest1 object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags of dest_object_name2. The tags of dest_object_name2 are the tags specified by headers[OSS_OBJECT_TAGGING].
    result = bucket.get_object_tagging(dest_object_name2)
    for key in result.tag_set.tagging_rule:
        print('dest2 object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • Set tags during a multipart copy

    The following code shows how to set object tags when you copy an object that is larger than 1 GB.

    # -*- coding: utf-8 -*-
    
    import os
    import oss2
    from oss2 import determine_part_size
    from oss2.models import PartInfo
    from oss2.headers import OSS_OBJECT_TAGGING
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    # Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    # Enter the bucket name.
    bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Enter the full path of the source object. The full path cannot include the bucket name. For example, enter srcexampledir/exampleobject.txt.
    src_object_name = 'srcexampledir/exampleobject.txt'
    # Enter the full path of the destination object. The full path cannot include the bucket name. For example, enter destexampledir/exampleobject.txt.
    dest_object_name = 'destexampledir/exampleobject.txt'
    
    # Get the size of the source object.
    head_info = bucket.head_object(src_object_name)
    total_size = head_info.content_length
    print('src object size:', total_size)
    
    # The determine_part_size method determines the part size.
    part_size = determine_part_size(total_size, preferred_size=100 * 1024)
    print('part_size:', part_size)
    
    # Set the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If a tag contains special characters, URL-encode the key and value of the tag.
    k4 = "k4+-="
    v4 = "+-=._:/"
    tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Set the tag information in the HTTP header.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Initialize the multipart upload.
    # Specify headers when you call the init_multipart_upload operation to add tags to the destination object.
    upload_id = bucket.init_multipart_upload(dest_object_name, headers=headers).upload_id
    parts = []
    
    # Upload parts one by one.
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
        end = offset + num_to_upload - 1;
        result = bucket.upload_part_copy(bucket.bucket_name, src_object_name, (offset, end), dest_object_name, upload_id, part_number)
        #Save the part information.
        parts.append(PartInfo(part_number, result.etag))
    
        offset += num_to_upload
        part_number += 1
    
    # Complete the multipart upload.
    result = bucket.complete_multipart_upload(dest_object_name, upload_id, parts)
    
    # Get the object metadata.
    head_info = bucket.head_object(dest_object_name)
    
    # View the size of the destination object.
    dest_object_size = head_info.content_length
    print('dest object size:', dest_object_size)
    
    # Compare the size with the source object.
    assert dest_object_size == total_size
    
    # View the tags of the source object.
    result = bucket.get_object_tagging(src_object_name)
    for key in result.tag_set.tagging_rule:
        print('src tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags of the destination object.
    result = bucket.get_object_tagging(dest_object_name)
    for key in result.tag_set.tagging_rule:
        print('dest tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))                   

Set tags for a symbolic link

The following code shows how to set tags for a symbolic link.

# -*- coding: utf-8 -*-

import oss2
from oss2.headers import OSS_OBJECT_TAGGING
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Enter the bucket name.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Enter the full path of the destination object. The full path cannot include the bucket name. For example, enter exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'
# Enter the full path of the symbolic link. For example, enter shortcut/myobject.txt.
symlink_name = 'shortcut/myobject.txt'

# Set the tagging string.
tagging = "k1=v1&k2=v2&k3=v3"

# If a tag contains special characters, URL-encode the key and value of the tag.
k4 = "k4+-="
v4 = "+-=._:/"
tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)

# Set the tag information in the HTTP header.
headers = dict()
headers[OSS_OBJECT_TAGGING] = tagging

# Create a symbolic link.
# Specify headers when you call the put_symlink operation to add tags to the symbolic link.
result = bucket.put_symlink(object_name, symlink_name, headers=headers)
print('http response status: ', result.status)

# View the tags of the symbolic link.
result = bucket.get_object_tagging(symlink_name)
for key in result.tag_set.tagging_rule:
    print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))

References

  • For the complete sample code for setting object tags, see the GitHub example.

  • For more information about the API operation to set object tags, see PutObjectTagging.