

文件AWS開發套件範例 GitHub 儲存庫中有更多可用的 [AWSSDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# `PutObjectAnnotation` 搭配 AWSSDK 使用
<a name="s3_example_s3_PutObjectAnnotation_section"></a>

以下程式碼範例顯示如何使用 `PutObjectAnnotation`。

動作範例是大型程式的程式碼摘錄，必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作：
+  [管理物件註釋](s3_example_s3_Scenario_ObjectAnnotations_section.md) 

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object_annotations#code-examples)中設定和執行。

```
    def put_object_annotation(
        self,
        bucket_name: str,
        object_key: str,
        annotation_name: str,
        annotation_payload: str,
    ) -> dict:
        """
        Attaches a named annotation payload to an S3 object.

        :param bucket_name: The name of the bucket containing the object.
        :param object_key: The key of the object to annotate.
        :param annotation_name: The name of the annotation (1-512 bytes).
        :param annotation_payload: The annotation content (1 byte to 1 MiB).
        :return: A dict containing the PutObjectAnnotation response with ETag.
        :raises ClientError: If the annotation name is invalid
                             (InvalidAnnotationName) or another error occurs.
        """
        try:
            response = self.s3_client.put_object_annotation(
                Bucket=bucket_name,
                Key=object_key,
                AnnotationName=annotation_name,
                AnnotationPayload=annotation_payload.encode("utf-8"),
            )
            logger.info(
                "Put annotation '%s' on object '%s' in bucket '%s'. ETag: %s",
                annotation_name,
                object_key,
                bucket_name,
                response.get("ETag", "N/A"),
            )
            return response
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAnnotationName":
                logger.error(
                    "Annotation name '%s' is invalid. Names must be 1-512 bytes, "
                    "UTF-8 encoded, and cannot start with 'aws' or 's3'.",
                    annotation_name,
                )
            raise
```
+  如需 API 詳細資訊，請參閱《適用於 *AWSPython (Boto3) 的 SDK API 參考*》中的 [PutObjectAnnotation](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObjectAnnotation)。

------