All Products
Search
Document Center

Content Moderation:Image Moderation 2.0 SDKs and usage guide

Last Updated:Nov 27, 2025

You can call the Image Moderation 2.0 API using SDKs or native HTTPS requests. We recommend that you use an SDK to call the API to simplify tasks such as signature verification and request body construction. This topic describes how to use Image Moderation 2.0.

Step 1: Activate the service

Go to the Activate Service page to activate the Image Moderation V2.0 service.

After you activate the Image Moderation 2.0 service, the default billing method is pay-as-you-go. Daily fees are calculated based on your actual usage. You are not charged if you do not call the service. When you call API operations, the billing system automatically charges you based on your usage. For more information, see Billing details.

Step 2: Create a RAM user and grant permissions

Before you use SDKs to call the Content Moderation API, you must create a user, obtain the access credential associated with the user, and grant the user the permissions to access Alibaba Cloud resources. In this example, a Resource Access Management (RAM) user is created, an AccessKey pair is used as the access credential, and the RAM user is granted the permission to call the Content Moderation

  1. Log on to the RAM console by using an Alibaba Cloud account or a RAM user that has administrative rights.

  2. Create a RAM user, select OpenAPI Access, and record the AccessKey pair that is generated for the RAM user. For more information about how to create a RAM user, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. For more information, see Grant permissions to a RAM user.

Step 3: Install and use an SDK

The following regions are supported for access:

Region

Public endpoint

VPC endpoint

Supported services

Singapore

https://green-cip.ap-southeast-1.aliyuncs.com

https://green-cip-vpc.ap-southeast-1.aliyuncs.com

postImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global

UK (London)

https://green-cip.eu-west-1.aliyuncs.com

Not available

US (Virginia)

https://green-cip.us-east-1.aliyuncs.com

https://green-cip-vpc.us-east-1.aliyuncs.com

baselineCheck_global, aigcDetector_global

US (Silicon Valley)

https://green-cip.us-west-1.aliyuncs.com

Not available

Germany (Frankfurt)

green-cip.eu-central-1.aliyuncs.com

Not available

Note

If you need SDK sample code in other programming languages, you can use the OpenAPI Explorer online debugging tool to test an API operation. This tool automatically generates SDK sample code for the API operation.

In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.

For a description of the API operation fields, see Image Moderation Enhanced V2.0 synchronous detection API.

Java SDK

Usage notes

Note

For information about the values and meanings of the Label field returned by the following operations, see Risk label reference.

Moderate an image that can be accessed over the Internet

Scenario

If the image to be moderated is accessible over the Internet, the Image Moderation Version 2.0 service can retrieve the image from the image URL for moderation.

  1. Add the following dependencies to the pom.xml file to install the Java SDK. You can then use the SDK in a Maven project.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  2. Use the Java SDK.

    • Synchronous API access example

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageUrlDemo {
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Set an HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set an HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: To improve detection performance, reuse the instantiated client to avoid repeatedly establishing connections.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeObject instance and set runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct the detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // A publicly accessible URL.
              serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
              // The unique identifier of the data to be detected.
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image detection service: The serviceCode configured for the Image Moderation Enhanced rule in the Content Moderation console. Example: baselineCheck_global.
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account AccessKey has full permissions on all API operations. We recommend that you use a RAM user for API access or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
      
              // Print the detection results.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      }

Moderate a local image

Scenario

If the image that you want to moderate is stored on your local computer and is not accessible over the Internet, you can upload the image to an Object Storage Service (OSS) bucket provided by the Content Moderation service. The Image Moderation 2.0 service can directly access OSS to retrieve the image content for moderation.

  1. Install the Java SDK.

    Install the Content Moderation SDK:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>

    Install the OSS SDK:

    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. Use the Java SDK.

    • Synchronous API access example

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ScanLocalImage {
      
          // Specifies whether the service is deployed in a VPC.
          public static boolean isVPC = false;
      
          // The token used to upload the file. The key is the endpoint and the value is the token.
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          // The client used to upload the file.
          public static OSS ossClient = null;
      
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * Create a client to upload the file.
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              // Note: To improve detection performance, reuse the instantiated client to avoid repeatedly establishing connections.
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * Upload the file.
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: To improve detection performance, reuse the instantiated client to avoid repeatedly establishing connections.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              // The full path of the local file. Example: D:\localPath\exampleFile.png.
              String filePath = "D:\localPath\exampleFile.png";
              // Obtain the token used to upload the file.
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint,tokenResponse.getBody().getData());
              }
              // The client used to upload the file.
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              // Upload the file.
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // Construct the detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // The information about the file upload.
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image detection service: The serviceCode configured for the Image Moderation Enhanced rule in the Content Moderation console. Example: baselineCheck.
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account AccessKey has full permissions on all API operations. We recommend that you use a RAM user for API access or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              // Modify the region and endpoint as needed.
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
              try {
                  // Print the detection results.
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              List<ImageModerationResponseBodyDataResult> results = data.getResult();
                              for (ImageModerationResponseBodyDataResult result : results) {
                                  System.out.println("label=" + result.getLabel());
                                  System.out.println("confidence=" + result.getConfidence());
                              }
                          } else {
                              System.out.println("image moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Moderate an image stored in OSS

Scenario

If the images that you want to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service-linked role (SLR) to allow the Content Moderation service to access OSS. The Image Moderation 2.0 service uses the SLR to retrieve files from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page to grant permissions.

  2. Add the following dependencies to the pom.xml file to install the Java SDK. You can then use the SDK in a Maven project.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  3. Use the Java SDK.

    • Synchronous API access example

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class OssScanDemo {
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Set an HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set an HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: To improve detection performance, reuse the instantiated client to avoid repeatedly establishing connections.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeObject instance and set runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct the detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // The unique identifier of the data to be detected.
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              // The region where the bucket of the image to be detected is located. Example: ap-southeast-1.
              serviceParameters.put("ossRegionId", "ap-southeast-1");
              // The name of the bucket where the image to be detected is stored. Example: bucket001.
              serviceParameters.put("ossBucketName", "bucket001");
              // The image to be detected. Example: image/001.jpg.
              serviceParameters.put("ossObjectName", "image/001.jpg");
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image detection service: The serviceCode configured for the Image Moderation Enhanced rule in the Content Moderation console. Example: baselineCheck_global.
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account AccessKey has full permissions on all API operations. We recommend that you use a RAM user for API access or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
      
              // Print the detection results.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
          }
      }

Python SDK

Usage notes

  • Prerequisites: Python 3.6 or later.

  • Source code: For more information, see SDK source code for Python.

  • Features: The SDK supports the following three types of image moderation.

Note

For information about the values and meanings of the Label field returned by the following operations, see Risk label reference.

Moderate publicly accessible images

Scenario

If an image that you want to moderate is accessible using a public URL, the Image Moderation 2.0 service can retrieve the image by its URL for moderation.

  1. Run the following command to import the required dependencies.

    pip install alibabacloud_green20220302==2.2.11
  2. Use the Python SDK.

    • Synchronous API access example

      # coding=utf-8
      
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      
      # Create a request client. 
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set the runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct the moderation parameters.
          service_parameters = {
              # The URL of the publicly accessible image.
              'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              # The unique ID of the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode of the rule configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An AccessKey pair of an Alibaba Cloud account has full permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          # For security reasons, do not store the AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all your cloud resources.
          # Common methods to obtain environment variables:
          # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of a RAM user from an environment variable.'
          access_key_secret='We recommend that you obtain the AccessKey secret of a RAM user from an environment variable.'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the result.
          if response is not None:
              if response.status_code == 200:
                  # The call is successful.
                  # Obtain the moderation result.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

Using local images for detection

Scenario

If an image that you want to moderate is on a local machine and does not have a public URL, you can upload the image to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation 2.0 service can then directly access OSS to retrieve the image for moderation.

  1. Install the Python SDK.

    Install the Content Moderation SDK:

    pip install alibabacloud_green20220302==2.2.11

    Install the OSS SDK:

    pip install oss2
  2. Use the Python SDK.

    • Synchronous API access example

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      import oss2
      import time
      import os
      
      # Specifies whether the service is deployed in a VPC.
      is_vpc = False
      # The token for file upload. endpoint->token.
      token_dict = dict()
      # The client for file upload.
      bucket = None
      
      
      # Create a request client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      # Create a file upload client.
      def create_oss_bucket(is_vpc, upload_token):
          global token_dict
          global bucket
          auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
          if (is_vpc):
              end_point = upload_token.oss_internal_end_point
          else:
              end_point = upload_token.oss_internet_end_point
          # Note: To improve moderation performance, reuse the instantiated bucket to avoid repeatedly establishing connections.
          bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      
      def upload_file(file_name, upload_token):
          create_oss_bucket(is_vpc, upload_token)
          object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set the runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # The full path of the local file. Example: D:\localPath\exampleFile.png.
          file_path = 'D:\localPath\exampleFile.png'
      
          # Obtain the token for file upload.
          upload_token = token_dict.setdefault(endpoint, None)
          if (upload_token == None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
              upload_token = response.body.data
              token_dict[endpoint] = upload_token
          # Upload the file.
          object_name = upload_file(file_path, upload_token)
      
          # Construct the moderation parameters.
          service_parameters = {
              # The name of the bucket that stores the file to moderate.
              'ossBucketName': upload_token.bucket_name,
              # The file to moderate.
              'ossObjectName': object_name,
              # The unique ID of the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode of the rule configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An AccessKey pair of an Alibaba Cloud account has full permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          # For security reasons, do not store the AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all your cloud resources.
          # Common methods to obtain environment variables:
          # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of a RAM user from an environment variable.'
          access_key_secret='We recommend that you obtain the AccessKey secret of a RAM user from an environment variable.'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the result.
          if response is not None:
              if response.status_code == 200:
                  # The call is successful.
                  # Obtain the moderation result.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

Moderate images stored in OSS

Scenario

If the image that you want to moderate is already stored in Alibaba Cloud Object Storage Service (OSS), you can grant permissions to create a service role. This allows the Content Moderation service to access OSS. The Image Moderation 2.0 service uses this service role to retrieve the image from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page and grant the required permissions.

  2. Run the following command to install the Python SDK.

    pip install alibabacloud_green20220302==2.2.11
  3. Use the Python SDK.

    • Synchronous API access example

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import os
      import uuid
      
      
      # Create a request client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set the runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct the moderation parameters.
          service_parameters = {
              # The region where the bucket that stores the file to moderate is located. Example: ap-southeast-1.
              'ossRegionId': 'ap-southeast-1',
              # The name of the bucket that stores the file to moderate. Example: bucket001.
              'ossBucketName': 'bucket001',
              # The file to moderate. Example: image/001.jpg.
              'ossObjectName': 'image/001.jpg',
              # The unique ID of the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode of the rule configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An AccessKey pair of an Alibaba Cloud account has full permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          # For security reasons, do not store the AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all your cloud resources.
          # Common methods to obtain environment variables:
          # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of a RAM user from an environment variable.'
          access_key_secret='We recommend that you obtain the AccessKey secret of a RAM user from an environment variable.'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the result.
          if response is not None:
              if response.status_code == 200:
                  # The call is successful.
                  # Obtain the moderation result.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

PHP SDK

Usage notes

  • Prerequisites: PHP 5.6 or later.

  • Source code: For more information, see PHP SDK source code.

  • Features: The SDK supports the following three types of image moderation.

Note

For information about the values and meanings of the Label field returned by the following API operations, see Risk Label Definitions.

Moderate an image that is accessible over the Internet

Scenario

If the image to be moderated is accessible using a public URL, the Image Moderation Version 2.0 service can retrieve the file from the image URL for moderation.

  1. Install the PHP SDK.

    Run the following command to import the required dependencies.

    composer require alibabacloud/green-20220302 2.2.10
  2. Use the PHP SDK.

    • Synchronous API access example

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
          		// Set an HTTP proxy.
          		// "httpProxy" => "http://10.10.xx.xx:xxxx",
          		// Set an HTTPS proxy.
          		// "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a moderation task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct moderation parameters.
          $request = new ImageModerationRequest();
          $serviceParameters = array(
              // The URL of the image to moderate. The image must be accessible over the Internet.
              'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              // The unique ID of the data to moderate.
              'dataId' => uniqid());
          // Image moderation service: The serviceCode of the rule that is configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
          $request->service = "baselineCheck_global";
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit the moderation task.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
      * Do not hardcode the AccessKey ID and AccessKey secret in your project code. This can lead to leaks and compromise the security of all your resources.
      * Obtain them from environment variables:
      * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'Obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'Obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Moderate a local image

Scenario

If the image that you want to moderate is stored on your local computer and is not accessible over the Internet, you can upload the image to an Object Storage Service (OSS) bucket provided by the Content Moderation service. The Image Moderation 2.0 service can directly access OSS to retrieve the image for moderation.

  1. Install the PHP SDK.

    Install the Content Moderation SDK:

    composer require alibabacloud/green-20220302 2.2.10

    Install the OSS SDK:

    composer require aliyuncs/oss-sdk-php
  2. Use the PHP SDK.

    • Synchronous API access example

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use OSS\OssClient;
      
      // Specifies whether the service is deployed in a VPC.
      $isVPC = false;
      // The token for file upload.
      $tokenArray = array();
      // The client for file upload requests.
      $ossClient = null;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
          		// Set an HTTP proxy.
         			// "httpProxy" => "http://10.10.xx.xx:xxxx",
         		 	// Set an HTTPS proxy.
         			// "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Create a file upload client.
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
          global $isVPC;
          global $ossClient;
          // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * Upload the file.
       * @param $fileName
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          // Initialize an OssClient instance.
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          // Upload the file.
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * Submit a moderation task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          global $tokenArray;
          // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // The full path of the local file. Example: D:\\localPath\\exampleFile.png.
          $filePath = "D:\\localPath\\exampleFile.png";
      
          // Obtain a file upload token.
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // Upload the file.
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // Construct moderation parameters.
          $request = new ImageModerationRequest();
          // Image moderation service: The serviceCode of the rule that is configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
          $request->service = "baselineCheck_global";
          // The OSS information of the image to moderate.
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit the moderation task.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
      * Do not hardcode the AccessKey ID and AccessKey secret in your project code. This can lead to leaks and compromise the security of all your resources.
      * Obtain them from environment variables:
      * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'Obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'Obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Moderate an image stored in OSS

Scenario

If the image files that you want to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can grant permissions to create a service role that allows the Content Moderation service to access OSS. The Image Moderation 2.0 service uses the service role to retrieve files from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page to grant the permissions.

  2. Install the PHP SDK.

    composer require alibabacloud/green-20220302 2.2.10
  3. Use the PHP SDK.

    • Synchronous API access example

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // Set an HTTP proxy.
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // Set an HTTPS proxy.
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a moderation task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct moderation parameters.
          $request = new ImageModerationRequest();
          $serviceParameters = array(
            	// The file to moderate. Example: image/001.jpg.
              'ossObjectName' => 'image/001.jpg',
              // The region of the bucket where the file to moderate is stored. Example: ap-southeast-1.
              'ossRegionId' => 'ap-southeast-1',
            	// The name of the bucket where the file to moderate is stored. Example: bucket001.
              'ossBucketName' => 'bucket001',
              // The unique ID of the data to moderate.
              'dataId' => uniqid());
          // Image moderation service: The serviceCode of the rule that is configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
          $request->service = "baselineCheck_global";
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit the moderation task.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. For security, use a RAM user to call API operations or perform routine O&M.
      * Do not hardcode the AccessKey ID and AccessKey secret in your project code. This can lead to leaks and compromise the security of all your resources.
      * Obtain them from environment variables:
      * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'Obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'Obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Go SDK

Usage notes

  • Source code: For more information, see Go SDK source code.

  • Features: The SDK supports the following three types of image moderation.

Note

For information about the values and meanings of the Label field returned by the following API operations, see Description of Threat Labels.

Moderate an image that is accessible over the Internet

Scenario

If the image to be moderated is accessible over the Internet, Image Moderation 2.0 can retrieve the image from the image URL for moderation.

  1. Install the Go SDK.

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  2. Use the Go SDK.

    • Synchronous API access example

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      // Create a client to send requests.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Set runtime parameters. The settings are valid only for requests that use this runtime instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Construct an image moderation request.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			// The URL of the image to moderate. The image must be accessible over the Internet.
      			"imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png",
      			// The ID of the data to moderate.
      			"dataId":uuid.New(),
      		},
      	)
      	imageModerationRequest := &green20220302.ImageModerationRequest{
      		// The image moderation service. This is the service code that you configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
      		Service:           tea.String("baselineCheck_global"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An AccessKey pair grants full access to all APIs. For security, use a RAM user for API calls and daily O&M.
      	 * Do not hard-code your AccessKey ID and AccessKey secret into your project. Hard-coding your credentials can lead to leaks and compromise the security of all your resources.
      	 * You can obtain credentials from environment variables:
      	 * Get the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= tea.String("Obtain the AccessKey ID of your RAM user from an environment variable.");
      	var accessKeySecret= tea.String("Obtain the AccessKey secret of your RAM user from an environment variable.");
      	// Modify the region and endpoint as needed.
      	var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Moderate a local image

Scenario

If the image that you want to moderate is on a local machine and does not have a public URL, you can upload the image to an Object Storage Service (OSS) bucket provided by Content Moderation. Image Moderation 2.0 can then directly access OSS to retrieve the image content for moderation.

  1. Install the Go SDK.

    Install the Content Moderation SDK:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2

    Install the OSS SDK:

    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Use the Go SDK.

    • Synchronous API access example

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      	"strings"
      	"time"
      )
      // The token for file upload.
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      // The client for file upload.
      var Bucket *oss.Bucket
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false
      // Create a client to send requests.
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: tea.String(accessKeyId),
      		AccessKeySecret: tea.String(accessKeySecret),
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: tea.String(endpoint),
      	}
      	// Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
      	return green20220302.NewClient(config);
      }
      
      // Create a client to upload files.
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
      	if isVPC{
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}else {
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}
      }
      
      // Upload the file.
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
      	createOssClient(tokenData)
      	objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
      	// Upload the file.
      	_err := Bucket.PutObjectFromFile(objectName, filePath)
      	if _err != nil {
      		fmt.Println("Error:", _err)
      		os.Exit(-1)
      	}
      	return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Set runtime parameters. The settings are valid only for requests that use this runtime instance.
      	runtime := &util.RuntimeOptions{}
      	// The full path of the local file. Example: D:\\localPath\\exampleFile.png.
      	var filePath = "D:\\localPath\\exampleFile.png"
      	// Obtain a temporary token for file upload.
      	tokenData,ok:=TokenMap[endpoint];
      	if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
      		// Obtain a temporary token for file upload.
      		uploadTokenResponse, _err := client.DescribeUploadToken()
      		if _err != nil {
      			return nil,_err
      		}
      		tokenData = uploadTokenResponse.Body.Data
      		TokenMap[endpoint] = tokenData
      	}
      	var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
      	// Construct an image moderation request.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
      			"ossObjectName": objectName,
      			"dataId":   uuid.New().String(),
      		},
      	)
      	imageModerationRequest := &green20220302.ImageModerationRequest{
      		// The image moderation service. This is the service code that you configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global.
      		Service:           tea.String("baselineCheck_global"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An AccessKey pair grants full access to all APIs. For security, use a RAM user for API calls and daily O&M.
      	 * Do not hard-code your AccessKey ID and AccessKey secret into your project. Hard-coding your credentials can lead to leaks and compromise the security of all your resources.
      	 * You can obtain credentials from environment variables:
      	 * Get the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= "Obtain the AccessKey ID of your RAM user from an environment variable.";
      	var accessKeySecret= "Obtain the AccessKey secret of your RAM user from an environment variable.";
      	// Modify the region and endpoint as needed.
      	var endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Moderate an image in OSS

Scenario

If the image that you want to moderate is already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service-linked role (SLR) to allow Content Moderation to access OSS. Image Moderation 2.0 uses the SLR to retrieve the file from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole SLR.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page and grant the required permissions.

  2. Run the following command to install the Go SDK.

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  3. Use the Go SDK.

    • Synchronous API access example

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      // Create a request client.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// Note: We recommend that you reuse the client instance to avoid repeatedly establishing connections and to improve detection performance.
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: We recommend that you reuse the client instance to avoid repeatedly establishing connections and to improve detection performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Configure runtime parameters. The settings are valid only for requests that use this runtime parameter instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Build an image moderation request.
      		serviceParameters, _ := json.Marshal(
      			map[string]interface{}{
      				// The region where the OSS bucket of the image to be moderated is located. Example: ap-southeast-1
      				"ossRegionId": "ap-southeast-1",
      				// The name of the OSS bucket of the image to be moderated. Example: bucket001
      				"ossBucketName":"bucket001",
      				// The name of the Object of the image to be moderated. Example: image/001.jpg
      				"ossObjectName":"image//001.jpg",
      				// The ID of the data to be moderated.
      				"dataId":   uuid.New().String(),
      			},
      		)
      		imageModerationRequest := &green20220302.ImageModerationRequest{
      			// The image moderation service. This is the serviceCode for the image moderation enhancement rule that you configured in the console. Example: baselineCheck_global
      			Service:           tea.String("baselineCheck_global"),
      			ServiceParameters: tea.String(string(serviceParameters)),
      		}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
      	 * We strongly recommend that you do not save your AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account.
      	 * Common methods to obtain environment variables:
      	 * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	
      	// Modify the region and endpoint based on your actual requirements.
      	var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Node.js SDK

Prerequisites

  • Source code: For more information, see Node.js SDK source code.

  • Features: The SDK supports the following three types of image moderation.

Note

For information about the values and meanings of the Label field that is returned by the following API operations, see Risk label description.

Moderate an image that is accessible over the internet

Scenario

If the image that you want to moderate is accessible over the Internet, Image Moderation 2.0 can retrieve the image from its URL for moderation.

  1. Install the Node.js SDK.

    Run the following command to import the required dependencies.

    npm install @alicloud/green20220302@2.2.10
  2. Use the Node.js SDK.

    • Synchronous API access example

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connections and improve moderation performance.
          var client = new RPCClient({
      				/**
               * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
               * We strongly recommend that you do not store your AccessKey ID and AccessKey secret in your project code. Otherwise, your AccessKey pair may be leaked, which threatens the security of all your cloud resources.
               * Common methods to obtain environment variables:
               * Obtain the AccessKey ID of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * Obtain the AccessKey secret of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: 'Obtain the AccessKey ID of a RAM user from an environment variable.',
              accessKeySecret: 'Obtain the AccessKey secret of a RAM user from an environment variable.',
              // Change the region and endpoint as needed.
              endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Set an HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set an HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
          // Create an API request and set the parameters using the following code.
          var params = {
              // The image moderation service. This is the serviceCode that you configured for the rule in the Image Moderation 2.0 console. Example: baselineCheck_global.
              "Service": "baselineCheck_global",
              "ServiceParameters": JSON.stringify({
                  // The unique ID of the data.
                  "dataId": uuidv4(),
                  // The URL of the image to be moderated. The image must be accessible over the internet.
                  "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API operation to obtain the moderation result.
              var response = await client.request('ImageModeration', params, requestOption)
          } catch (err) {
              console.log(err);
          }
      
          return response;
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });

Detect local images

Scenario

If the image that you want to moderate is on a local machine and does not have a public URL, you can upload the image to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation 2.0 service can then directly access OSS to retrieve the image for moderation.

  1. Install the Node.js SDK.

    Install the Content Moderation SDK:

    npm install @alicloud/green20220302@2.2.10

    Install the OSS SDK:

    npm install ali-oss --save
  2. Use the Node.js SDK.

    • Synchronous API access example

      const RPCClient = require("@alicloud/pop-core");
      const OSS = require('ali-oss');
      const { v4: uuidv4 } = require('uuid');
      const path = require("path");
      
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false;
      // The token used to upload the file.
      var tokenDic = new Array();
      // The client used to upload the file.
      var ossClient;
      
      // Create a client to upload the file.
      function createClient(accessKeyId, accessKeySecret, endpoint) {
          return new RPCClient({
              accessKeyId: accessKeyId,
              accessKeySecret: accessKeySecret,
              endpoint: endpoint,
              apiVersion: '2022-03-02',
              // Set an HTTP proxy.
              //httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set an HTTPS proxy.
              //httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      }
      
      // Create a client to upload the file.
      function getOssClient(tokenData, isVPC) {
          if (isVPC) {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternalEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          } else {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternetEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          }
      }
      
      
      async function invoke(accessKeyId, accessKeySecret, endpoint) {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connections and improve moderation performance.
          var client = createClient(accessKeyId, accessKeySecret, endpoint);
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
          // The full path of the local file. Example: D:\\localPath\\exampleFile.png.
          var filePath = 'D:\\localPath\\exampleFile.png';
      
          // Obtain a token to upload the file.
          if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
              var tokenResponse = await client.request('DescribeUploadToken', '', requestOption)
              tokenDic[endpoint] = tokenResponse.Data;
          }
      
          // Obtain a client to upload the file.
          getOssClient(tokenDic[endpoint], isVPC)
          var split = filePath.split(".");
          var objectName;
          if (split.length > 1) {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1];
          } else {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4();
          }
          // Upload the file.
          const result = await ossClient.put(objectName, path.normalize(filePath));
      
          // Create a moderation API request and set the parameters using the following code.
          var params = {
              // The image moderation service. This is the serviceCode that you configured for the rule in the Image Moderation 2.0 console. Example: baselineCheck_global.
              "Service": "baselineCheck_global",
              // Information about the uploaded local image.
              "ServiceParameters": JSON.stringify({
                  "ossBucketName": tokenDic[endpoint].BucketName,
                  "ossObjectName": objectName
              })
          }
          // Call the API operation to obtain the moderation result.
          return await client.request('ImageModeration', params, requestOption);
      }
      
      
      
      function main() {
      	/**
          * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          * We strongly recommend that you do not store your AccessKey ID and AccessKey secret in your project code. Otherwise, your AccessKey pair may be leaked, which threatens the security of all your cloud resources.
          * Common methods to obtain environment variables:
          * Obtain the AccessKey ID of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
          * Obtain the AccessKey secret of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          */
          const accessKeyId = 'Obtain the AccessKey ID of a RAM user from an environment variable.';
          const accessKeySecret = 'Obtain the AccessKey secret of a RAM user from an environment variable.';
          // Change the region and endpoint as needed.
          var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com"
      
          try {
              // Call the API operation to obtain the moderation result.
              invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
                      console.log(JSON.stringify(response))
              })
          } catch (err) {
              console.log(err);
          }
      }
      
      main();

Moderate an image in OSS

Scenario

If the image that you want to moderate is already stored in Alibaba Cloud Object Storage Service (OSS), you can authorize Content Moderation to access your OSS resources by creating a service-linked role (SLR). The Image Moderation 2.0 service then uses the SLR to retrieve the image from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole SLR.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page to grant the permissions.

  2. Install the Node.js SDK.

    npm install @alicloud/green20220302@2.2.10
  3. Use the Node.js SDK.

    • Synchronous API access example

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connections and improve moderation performance.
          var client = new RPCClient({
      				/**
               * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
               * We strongly recommend that you do not store your AccessKey ID and AccessKey secret in your project code. Otherwise, your AccessKey pair may be leaked, which threatens the security of all your cloud resources.
               * Common methods to obtain environment variables:
               * Obtain the AccessKey ID of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * Obtain the AccessKey secret of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: 'Obtain the AccessKey ID of a RAM user from an environment variable.',
              accessKeySecret: 'Obtain the AccessKey secret of a RAM user from an environment variable.',
              // Change the region and endpoint as needed.
              endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Set an HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set an HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      
          // Create an API request and set the parameters using the following code.
          var params = {
              // The image moderation service. This is the serviceCode that you configured for the rule in the Image Moderation 2.0 console. Example: baselineCheck_global.
              "Service": "baselineCheck_global",
              // Information about the OSS image to be moderated.
              "ServiceParameters": JSON.stringify({
                  // The region where the bucket that stores the file is located. Example: ap-southeast-1.
                  "ossRegionId": "ap-southeast-1",
                  // The name of the bucket that stores the file. Example: bucket001.
                  "ossBucketName": "bucket001",
                  // The file to be moderated. Example: image/001.jpg.
                  "ossObjectName": "image/001.jpg",
                  // The unique ID of the data.
                  "dataId": uuidv4()
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API operation to obtain the moderation result.
              var response = await client.request('ImageModeration', params, requestOption)
              return response;
          } catch (err) {
              console.log(err);
          }
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });

C# SDK

Usage notes

  • Source code: For more information, see C# SDK source code.

  • Features: The SDK supports the following three types of image moderation.

Note

For information about the values and meanings of the Label field returned by the following API operations, see Risk label definitions.

Moderate an image that can be accessed over the Internet

Scenario

If the image to be moderated is accessible over the Internet, the Image Moderation Version 2.0 service can retrieve the file from the image URL for moderation.

  1. Install the C# SDK.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  2. Use the C# SDK.

    • Synchronous API access example

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform daily O&M.
                  * We strongly recommend that you do not save an AccessKey pair in the project code. Otherwise, the AccessKey pair may be leaked and all resources that are contained in your account may be exposed to potential security risks.
                  * Common methods for obtaining environment variables:
                  * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Obtain the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "Obtain your AccessKey ID from an environment variable";
                  String accessKeySecret = "Obtain your AccessKey secret from an environment variable";
                  // Modify the region and endpoint based on your actual requirements.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
                  // Note: We recommend that you reuse the client instance to avoid repeatedly establishing connections and to improve detection performance.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Configure runtime parameters. The parameters are valid only for requests that use the runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Create an image moderation request.
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  // The image moderation service. This value is the serviceCode that you configured for the image moderation rule in the Content Moderation console. Example: baselineCheck_global
                  imageModerationRequest.Service = "baselineCheck_global";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  // The URL of the image to be moderated. The URL must be accessible over the Internet.
                  task.Add(
                      "imageUrl",
                      "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
                  );
                  // The ID of the data to be moderated.
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      // Call the API operation to obtain the moderation result.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a request client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set the HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set the HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The endpoint to be accessed.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

Moderate a local image

Scenario

If the image that you want to moderate is stored on your local computer and is not accessible over the Internet, you can upload the image to an Object Storage Service (OSS) bucket provided by the Content Moderation service. Image Moderation Version 2.0 can directly access OSS to retrieve the image for moderation.

  1. Install the C# SDK.

    Install the Content Moderation SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10

    Install the OSS SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.8
    
    Install using NuGet 
    1. If NuGet is not installed in Visual Studio, install NuGet.
    2. In Visual Studio, create a new project or open an existing project. Choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
    3. Search for aliyun.oss.sdk. In the search results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .Net Core). Select the latest version and click Install.
  2. Use the C# SDK.

    • Synchronous API access example

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              // The file upload token.
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              // The file upload client.
              public static OssClient ossClient = null;
      
              // Specifies whether the service is deployed on a VPC.
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * An AccessKey for an Alibaba Cloud account has permissions to access all APIs. Use a Resource Access Management (RAM) user for API calls or routine O&M.
                  * Do not save your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey leak and compromise the security of all your resources.
                  * Common methods to obtain environment variables:
                  * Obtain the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Obtain the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "Obtain the AccessKey ID of the RAM user from an environment variable";
                  String accessKeySecret = "Obtain the AccessKey secret of the RAM user from an environment variable";
                  // Modify the region and endpoint as needed.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
                  Models.ImageModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
              
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              // Create a request client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set the HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set the HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The domain name to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              // Create a file upload client.
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              // Upload the file.
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // Create an OssClient instance.
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  // Upload the file.
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              // Submit a moderation request.
              public static Models.ImageModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  // Note: Reuse the instantiated client to avoid creating repeated connections and to improve moderation performance.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Runtime parameter settings. These settings are valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // The full path of the local file. For example, D:\localPath\exampleFile.png.
                  String filePath = "D:\\localPath\\exampleFile.png";
                  try
                  {
                      // Obtain a temporary token for file upload.
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      // Upload the file.
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      // Build an image moderation request.
                      Models.ImageModerationRequest imageModerationRequest =
                          new Models.ImageModerationRequest();
                      // Image moderation service: The serviceCode for the enhanced image moderation rule configured in the Content Moderation console. Example: baselineCheck_global.
                      imageModerationRequest.Service = "baselineCheck_global";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      // The information about the image to be moderated.
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      // The ID of the data to be moderated.
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      // Call the API to obtain the moderation result.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

Moderate images in OSS

Scenario

If you store images for moderation in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant Content Moderation access to OSS. The Image Moderation Version 2.0 service uses the service role to retrieve the files from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  1. Use your Alibaba Cloud account to go to the Cloud Resource Access Authorization page to grant the required permissions.

  2. Install the C# SDK.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  3. Use the C# SDK.

    • Synchronous API access example

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class OssScanDemo
          {
              public static void Main(string[] args)
              {
                  /**
                  * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
                  * Do not hard-code your AccessKey ID and AccessKey secret in your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
                  * You can obtain the AccessKey pair from environment variables:
                  * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Obtain the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "Obtain the AccessKey ID of a RAM user from an environment variable.";
                  String accessKeySecret = "Obtain the AccessKey secret of a RAM user from an environment variable.";
                  // Modify the region and endpoint as needed.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
                  // Note: To improve moderation performance, reuse the instantiated client to avoid repeated connections.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Configure runtime parameters. The settings are valid only for requests that use this runtime instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Construct an image moderation request.
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  // Image moderation service: the serviceCode that you configured for the rule in the Content Moderation console. Example: baselineCheck_global.
                  imageModerationRequest.Service = "baselineCheck_global";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  // The region where the OSS bucket of the image to be moderated is located. Example: ap-southeast-1.
                  task.Add("ossRegionId", "ap-southeast-1");
                  // The name of the OSS bucket that stores the image to be moderated. Example: bucket001.
                  task.Add("ossBucketName", "bucket001");
                  // The name of the object for the image to be moderated. Example: image/001.jpg.
                  task.Add("ossObjectName", "image/001.jpg");
                  // The ID of the data to be moderated.
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                  try
                  {
                      // Call the API operation to obtain the moderation result.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a client for sending requests.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set an HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set an HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The endpoint of the service.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

Native HTTPS calls

You can also call the Content Moderation 2.0 API service by making native HTTPS calls. This method requires you to handle signature generation and verification, and to construct the request, including the URL, body, header, and parameters. Use native HTTPS calls only in the following two scenarios. In other cases, we recommend that you use an SDK.

  1. You use the service directly in an app that has strict requirements on the client size.

  2. You have specific dependencies on certain library packages that are difficult to upgrade.

  • Call method

    Service endpoint: https://green-cip.{region}.aliyuncs.com

    Protocol: HTTPS

    Method: POST

  • Common request parameters

    The request parameters for Image Moderation 2.0 API operations include common request parameters and operation-specific request parameters. Common request parameters are required for every operation. The following table describes the common request parameters.

    Name

    Type

    Required

    Description

    Format

    String

    Yes

    The format of the response message. Valid values:

    • JSON (default)

    • XML

    Version

    String

    Yes

    The API version number. Use the YYYY-MM-DD format. Set the value to 2022-03-02.

    AccessKeyId

    String

    Yes

    The AccessKey ID provided by Alibaba Cloud for you to access the service.

    Signature

    String

    Yes

    The signature string. For information about how to calculate the signature, see the Signature method section below.

    SignatureMethod

    String

    Yes

    The signature method. Set the value to HMAC-SHA1.

    Timestamp

    String

    Yes

    The request timestamp. Specify the time in Coordinated Universal Time (UTC) and in the ISO 8601 standard format: `yyyy-MM-ddTHH:mm:ssZ`. For example, `2022-12-12T01:13:14Z` represents 09:13:14 on December 12, 2022 (UTC+8).

    SignatureVersion

    String

    Yes

    The version of the signature algorithm. Set the value to 1.0.

    SignatureNonce

    String

    Yes

    A unique random number used to prevent replay attacks. Use a different random number for each request.

    Action

    String

    Yes

    • Synchronous image moderation operation: ImageModeration

    • Asynchronous image moderation operation: ImageAsyncModeration

    • Operation to get asynchronous image moderation results: DescribeImageModerationResult

    • Synchronous multi-service image moderation operation: ImageBatchModeration

  • Common response parameters

    For each API call, the system returns a unique request ID, `RequestId`, regardless of whether the call is successful. Other response parameters include `label` and `confidence`. The response parameters vary based on the service. For more information, see the documentation for the specific service.

    Note

    For information about the values and meanings of the Label field returned by all operations, see Threat label definitions.

  • Code examples

    The following sample responses are formatted for readability. Actual responses are not formatted with line breaks or indentation.

    The following code provides a sample request for the synchronous baseline check service of Image Moderation 2.0. For other operations, see the documentation for that operation to get the required request parameters:

    https://green-cip.ap-southeast-1.aliyuncs.com/ 
        ?Format=JSON
        &Version=2022-03-02
        &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
        &SignatureMethod=Hmac-SHA1
        &SignatureNonce=15215528852396
        &SignatureVersion=1.0
        &Action=ImageModeration
        &AccessKeyId=123****cip
        &Timestamp=2022-12-12T12:00:00Z
        &Service=baselineCheck_global
        &ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png",
        "dataId": "img1234567"}

    The following code provides a sample JSON response from the synchronous baseline check service of Image Moderation 2.0:

    {
        "Msg": "OK",
        "Code": 200,
        "Data": {
            "DataId": "uimg123****",
            "Result": [
                {
                    "Label": "pornographic_adultContent",
                    "Confidence": 81.3
                },
                {
                    "Label": "sexual_partialNudity",
                    "Confidence": 98.9
                }
            ]
        },
        "RequestId": "ABCD1234-1234-1234-1234-1234XYZ"
    }
  • Signature method

    The Image Moderation 2.0 service authenticates each request. Therefore, you must include signature information in each request. The Image Moderation 2.0 service uses an AccessKey ID and an AccessKey secret to perform symmetric encryption and authenticate the request sender.

    Alibaba Cloud issues an AccessKey ID and an AccessKey secret to you. You can apply for and manage them on the Alibaba Cloud website. The AccessKey ID identifies you. The AccessKey secret is a key used to encrypt the signature string and verify the signature string on the server. You must keep your AccessKey secret confidential.

    To sign a request, you can perform the following steps:

    1. Create a canonicalized query string from the request parameters.

      1. Sort all request parameters alphabetically by parameter name. The parameters to be sorted include common request parameters and operation-specific parameters, but exclude the Signature parameter.

      2. URL-encode the names and values of the sorted parameters using the UTF-8 character set.

        Note

        Most libraries that support URL encoding, such as `java.net.URLEncoder` in Java, encode according to the `application/x-www-form-urlencoded` Multipurpose Internet Mail Extensions (MIME) type rules. You can use this encoding method. In the encoded string, you must replace plus signs (+) with `%20`, asterisks (*) with `%2A`, and `%7E` with tildes (~).

        The URL encoding rules are as follows:

        • Do not encode uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), hyphens (-), underscores (_), periods (.), or tildes (~).

        • Encode other characters into the %XY format, where XY is the two-digit hexadecimal value of the character's ASCII code. For example, a double quotation mark (") is encoded as %22.

        • Encode extended UTF-8 characters into the %XY%ZA… format.

        • Encode spaces as %20 instead of plus signs (+).

      3. Connect each encoded parameter name and its value with an equal sign (=).

      4. Connect the resulting name-value pairs with ampersands (&) in the same alphabetical order to create the canonicalized query string.

    2. Use the canonicalized query string from Step 1 to create the string-to-sign as follows:

      StringToSign=
      HTTPMethod + "&" +
      percentEncode("/") + "&" +
      percentEncode(CanonicalizedQueryString)
      Note

      `HTTPMethod` is the HTTP method used for the request, such as POST. `percentEncode("/")` is the value of a forward slash (/) encoded according to the URL encoding rules in Step 1.b. The value is %2F. `percentEncode(CanonicalizedQueryString)` is the string that you retrieve by encoding the canonicalized query string from Step 1 according to the URL encoding rules in Step 1.b.

    3. Calculate the hash-based message authentication code (HMAC) value of the string-to-sign as defined in RFC 2104.

      Note

      Use the SHA1 hash algorithm. The key for the HMAC calculation is your AccessKey secret appended with an ampersand (&) character (ASCII code 38).

    4. Encode the HMAC value in Base64 to obtain the signature string.

    5. Add the resulting signature string to the request parameters as the `Signature` parameter. This completes the request signing process.

      Note

      When you submit the signature value as the final request parameter to the Content Moderation server, you must URL-encode it as with other parameters, according to RFC 3986.