All Products
Search
Document Center

AI Guardrails:Image Moderation 2.0 SDK and Integration Guide

Last Updated:Mar 31, 2026

This guide walks you through activating Image Moderation 2.0, setting up credentials, and making your first moderation call. Two integration methods are supported: SDK (recommended) and native HTTPS. Use an SDK when possible — it handles signature authentication and request formatting automatically.

Prerequisites

Before you begin, ensure that you have:

  • An Alibaba Cloud account with sufficient permissions to create RAM users and activate services

Step 1: Activate the service

Go to the Activate Service page and activate Image Moderation 2.0.

The default billing method is pay-as-you-go — charges settle daily based on actual usage. If you make no API calls, you are not charged. For pricing details, see Billing details.

Step 2: Create a RAM user and grant permissions

  1. Log on to the RAM console with your Alibaba Cloud account or an admin RAM user.

  2. Create a RAM user: select OpenAPI Access as the access type, and record the AccessKey pair that is generated. See Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. See Grant permissions to a RAM user.

Step 3: Set up credentials

Store your AccessKey pair as environment variables so your code can read them without hardcoding secrets.

Linux / macOS

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Windows (Command Prompt)

set ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Replace <your-access-key-id> and <your-access-key-secret> with the values from Step 2.

For other credential configuration options, see Configure credentials.

Step 4: Install and call the SDK

Supported regions

RegionPublic endpointVPC endpointSupported service codes
Singaporegreen-cip.ap-southeast-1.aliyuncs.comgreen-cip-vpc.ap-southeast-1.aliyuncs.compostImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global
UK (London)green-cip.eu-west-1.aliyuncs.comNone
US (Virginia)green-cip.us-east-1.aliyuncs.comgreen-cip-vpc.us-east-1.aliyuncs.combaselineCheck_global, aigcDetector_global
US (Silicon Valley)green-cip.us-west-1.aliyuncs.comNone
Germany (Frankfurt)green-cip.eu-central-1.aliyuncs.comgreen-cip-vpc.eu-central-1.aliyuncs.com
For SDK sample code in other languages, use the OpenAPI Developer Portal to debug API operations — it auto-generates sample code for each language.

Choose your image source

The parameters you pass depend on where your images are stored:

Image sourceWhat to do
Publicly accessible URLPass the URL directly in the request
Local file (no public URL)Upload to Content Moderation's OSS bucket first, then pass the OSS object reference
File already in your OSS bucketGrant Content Moderation access to your bucket, then pass the OSS object reference

Understand the response

Every successful moderation call returns a Result array with one or more labels. Each label has two fields:

FieldDescription
LabelThe risk category detected (e.g., pornographic_adultContent, sexual_partialNudity). See Risk label descriptions for the full list.
ConfidenceA float between 0 and 100 indicating confidence in the label. Higher values indicate higher certainty.

Example response:

{
  "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"
}

Java SDK

Requirements: Java 1.8 or later

Source code: Java SDK on GitHub

Detect publicly accessible images

Images accessible via a public URL can be submitted directly to the API.

  1. Add the dependency to your pom.xml:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  2. Call the API:

Detect local images

Local images without a public URL must be uploaded to Content Moderation's OSS bucket before detection. The service retrieves the image from OSS for moderation.

  1. Add both dependencies to your pom.xml:

    <!-- Content Moderation SDK -->
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
    <!-- OSS SDK -->
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. Call the API:

    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 {
    
        // Set to true when running in a VPC environment.
        public static boolean isVPC = false;
    
        // Cache upload tokens by endpoint to avoid fetching a new token for every request.
        public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
    
        public static OSS ossClient = null;
    
        public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Config config = new Config();
            config.setAccessKeyId(accessKeyId);
            config.setAccessKeySecret(accessKeySecret);
            config.setEndpoint(endpoint);
            return new Client(config);
        }
    
        public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
            // Reuse the OSS client across requests.
            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());
            }
        }
    
        public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
            String[] split = filePath.split("\\.");
            String objectName = split.length > 1
                ? tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1]
                : 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 {
            // Reuse the client across requests.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            // Replace with the actual path to your local file.
            String filePath = "D:\\localPath\\exampleFile.png";
    
            // Fetch and cache the upload token; refresh it when it expires.
            if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                tokenMap.put(endpoint, tokenResponse.getBody().getData());
            }
            getOssClient(tokenMap.get(endpoint), isVPC);
    
            String objectName = uploadFile(filePath, tokenMap.get(endpoint));
    
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
            serviceParameters.put("ossObjectName", objectName);
            serviceParameters.put("dataId", UUID.randomUUID().toString());
    
            ImageModerationRequest request = new ImageModerationRequest();
            request.setService("baselineCheck_global");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
    
            try {
                return client.imageModerationWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public static void main(String[] args) throws Exception {
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
    
            if (response != null && response.getStatusCode() == 200) {
                ImageModerationResponseBody body = response.getBody();
                System.out.println("requestId=" + body.getRequestId());
                if (body.getCode() == 200) {
                    ImageModerationResponseBodyData data = body.getData();
                    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("Moderation failed. code=" + body.getCode());
                }
            }
        }
    }

Detect OSS images

Images already stored in your OSS bucket can be moderated directly without re-uploading. First, grant Content Moderation access to your bucket by creating the AliyunCIPScanOSSRole service role.

  1. Log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to grant the permission.

  2. Add the dependency to your pom.xml:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  3. Call the API:

    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 {
    
        public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Config config = new Config();
            config.setAccessKeyId(accessKeyId);
            config.setAccessKeySecret(accessKeySecret);
            // Optional: set HTTP/HTTPS proxy if needed
            // config.setHttpProxy("http://10.10.xx.xx:xxxx");
            // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
            config.setEndpoint(endpoint);
            return new Client(config);
        }
    
        public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            serviceParameters.put("ossRegionId", "ap-southeast-1");   // region where the bucket is located
            serviceParameters.put("ossBucketName", "bucket001");       // your OSS bucket name
            serviceParameters.put("ossObjectName", "image/001.jpg");   // object path in the bucket
    
            ImageModerationRequest request = new ImageModerationRequest();
            request.setService("baselineCheck_global");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
    
            try {
                return client.imageModerationWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public static void main(String[] args) throws Exception {
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
    
            if (response != null && response.getStatusCode() == 200) {
                ImageModerationResponseBody body = response.getBody();
                System.out.println("requestId=" + body.getRequestId());
                if (body.getCode() == 200) {
                    ImageModerationResponseBodyData data = body.getData();
                    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("Moderation failed. code=" + body.getCode());
                }
            }
        }
    }

Python SDK

Requirements: Python 3.6 or later

Source code: Python SDK on PyPI

Detect publicly accessible images

  1. Install the SDK:

    pip install alibabacloud_green20220302==2.2.11
  2. Call the API:

    # coding=utf-8
    
    import json
    import os
    import uuid
    
    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
    
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            # Optional: set HTTP/HTTPS proxy if needed
            # http_proxy='http://10.10.xx.xx:xxxx',
            # https_proxy='https://10.10.xx.xx:xxxx',
            endpoint=endpoint
        )
        return Client(config)
    
    
    def invoke_function(access_key_id, access_key_secret, endpoint):
        # Reuse the client across requests.
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        service_parameters = {
            'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',  # public URL
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            # Set the service code configured in the AI Guardrails console.
            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__':
        # Read credentials from environment variables — do not hardcode them.
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        # Change the endpoint to match your region.
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                result_data = result.data
                print('result:', result_data)
            else:
                print('Moderation failed. status:', response.status_code)

Detect local images

  1. Install both SDKs:

    pip install alibabacloud_green20220302==2.2.11
    pip install oss2
  2. Call the API:

    import json
    import os
    import time
    import uuid
    
    import oss2
    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
    
    
    # Set to True when running in a VPC environment.
    is_vpc = False
    # Cache upload tokens by endpoint to avoid fetching a new token for every request.
    token_dict = dict()
    bucket = None
    
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            endpoint=endpoint
        )
        return Client(config)
    
    
    def create_oss_bucket(is_vpc, upload_token):
        global bucket
        auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
        end_point = upload_token.oss_internal_end_point if is_vpc else upload_token.oss_internet_end_point
        # Reuse the bucket client across requests.
        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):
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        # Replace with the actual path to your local file.
        file_path = 'D:\\localPath\\exampleFile.png'
    
        # Fetch and cache the upload token; refresh it when it expires.
        upload_token = token_dict.setdefault(endpoint, None)
        if upload_token is None or int(upload_token.expiration) <= int(time.time()):
            response = client.describe_upload_token()
            upload_token = response.body.data
            token_dict[endpoint] = upload_token
    
        object_name = upload_file(file_path, upload_token)
    
        service_parameters = {
            'ossBucketName': upload_token.bucket_name,
            'ossObjectName': object_name,
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            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__':
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                print('result:', result.data)
            else:
                print('Moderation failed. status:', response.status_code)

Detect OSS images

  1. Grant Content Moderation access to your OSS bucket: log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  2. Install the SDK:

    pip install alibabacloud_green20220302==2.2.11
  3. Call the API:

    import json
    import os
    import uuid
    
    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
    
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            endpoint=endpoint
        )
        return Client(config)
    
    
    def invoke_function(access_key_id, access_key_secret, endpoint):
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        service_parameters = {
            'ossRegionId': 'ap-southeast-1',   # region where the bucket is located
            'ossBucketName': 'bucket001',       # your OSS bucket name
            'ossObjectName': 'image/001.jpg',   # object path in the bucket
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            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__':
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                print('result:', result.data)
            else:
                print('Moderation failed. status:', response.status_code)

PHP SDK

Requirements: PHP 5.6 or later

Source code: PHP SDK on Packagist

Detect publicly accessible images

  1. Install the SDK:

    composer require alibabacloud/green-20220302 2.2.10
  2. Call the API:

Detect local images

  1. Install both SDKs:

    composer require alibabacloud/green-20220302 2.2.10
    composer require aliyuncs/oss-sdk-php
  2. Call the API:

    <?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 OSS\OssClient;
    
    // Set to true when running in a VPC environment.
    $isVPC = false;
    // Cache upload tokens by endpoint.
    $tokenArray = array();
    $ossClient = null;
    
    function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    function create_upload_client($tokenData): void
    {
        global $isVPC, $ossClient;
        // Reuse the OSS client across requests.
        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);
        }
    }
    
    function upload_file($filePath, $tokenData): string
    {
        global $ossClient;
        create_upload_client($tokenData);
        $split = explode(".", $filePath);
        $objectName = count($split) > 1
            ? $tokenData->fileNamePrefix . uniqid() . "." . end($split)
            : $tokenData->fileNamePrefix . uniqid();
        $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
        return $objectName;
    }
    
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
    {
        global $tokenArray;
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        $runtime = new RuntimeOptions([]);
    
        // Replace with the actual path to your local file.
        $filePath = "D:\\localPath\\exampleFile.png";
    
        // Fetch and cache the upload token; refresh it when it expires.
        if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
            $token = $client->describeUploadToken();
            $tokenArray[$endpoint] = $token->body->data;
        }
    
        $objectName = upload_file($filePath, $tokenArray[$endpoint]);
    
        $request = new ImageModerationRequest();
        $request->service = "baselineCheck_global";
        $serviceParameters = array(
            'ossObjectName' => $objectName,
            'ossBucketName' => $tokenArray[$endpoint]->bucketName,
            'dataId' => uniqid()
        );
        $request->serviceParameters = json_encode($serviceParameters);
        return $client->imageModerationWithOptions($request, $runtime);
    }
    
    $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    $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());
    }

Detect OSS images

  1. Grant Content Moderation access to your OSS bucket: log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  2. Install the SDK:

    composer require alibabacloud/green-20220302 2.2.10
  3. Call the API:

Go SDK

Source code: Go SDK on GitHub

Detect publicly accessible images

  1. Install the SDK:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  2. Call the API:

Detect local images

  1. Install both SDKs:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Call the API:

    package main
    
    import (
        "encoding/json"
        "fmt"
        openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
        green20220302 "github.com/alibabacloud-go/green-20220302/v3/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"
    )
    
    // Cache upload tokens by endpoint.
    var TokenMap = make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
    
    // Set to true when running in a VPC environment.
    var isVPC = false
    var Bucket *oss.Bucket
    
    func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
        config := &openapi.Config{
            AccessKeyId:     tea.String(accessKeyId),
            AccessKeySecret: tea.String(accessKeySecret),
            Endpoint:        tea.String(endpoint),
        }
        return green20220302.NewClient(config)
    }
    
    func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
        var endPoint string
        if isVPC {
            endPoint = tea.StringValue(tokenData.OssInternalEndPoint)
        } else {
            endPoint = tea.StringValue(tokenData.OssInternetEndPoint)
        }
        ossClient, err := oss.New(endPoint, 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))
    }
    
    func uploadFile(filePath string, tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string, error) {
        createOssClient(tokenData)
        objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
        _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) {
        client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
        if _err != nil {
            return nil, _err
        }
        runtime := &util.RuntimeOptions{}
    
        // Replace with the actual path to your local file.
        var filePath = "D:\\localPath\\exampleFile.png"
    
        // Fetch and cache the upload token; refresh it when it expires.
        tokenData, ok := TokenMap[endpoint]
        if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
            uploadTokenResponse, _err := client.DescribeUploadToken()
            if _err != nil {
                return nil, _err
            }
            tokenData = uploadTokenResponse.Body.Data
            TokenMap[endpoint] = tokenData
        }
    
        objectName, _ := uploadFile(filePath, TokenMap[endpoint])
    
        serviceParameters, _ := json.Marshal(
            map[string]interface{}{
                "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
                "ossObjectName": objectName,
                "dataId":        uuid.New().String(),
            },
        )
        imageModerationRequest := &green20220302.ImageModerationRequest{
            Service:           tea.String("baselineCheck_global"),
            ServiceParameters: tea.String(string(serviceParameters)),
        }
    
        return client.ImageModerationWithOptions(imageModerationRequest, runtime)
    }
    
    func main() {
        accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
        accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        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
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == http.StatusOK {
                if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                    result := body.Data.Result
                    for i := 0; i < len(result); i++ {
                        fmt.Println("label:" + tea.StringValue(result[i].Label))
                        fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                    }
                } else {
                    fmt.Println("Moderation failed. code:", body.Code)
                }
            } else {
                fmt.Println("Request failed. status:", statusCode, "error:", _err)
            }
        }
    }

Detect OSS images

  1. Grant Content Moderation access to your OSS bucket: log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  2. Install the SDK:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  3. Call the API:

    package main
    
    import (
        "encoding/json"
        "fmt"
        openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
        green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
        util "github.com/alibabacloud-go/tea-utils/v2/service"
        "github.com/alibabacloud-go/tea/tea"
        "github.com/google/uuid"
        "net/http"
        "os"
    )
    
    func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
        config := &openapi.Config{
            AccessKeyId:     accessKeyId,
            AccessKeySecret: accessKeySecret,
            Endpoint:        endpoint,
        }
        return green20220302.NewClient(config)
    }
    
    func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
        client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
        if _err != nil {
            return nil, _err
        }
        runtime := &util.RuntimeOptions{}
    
        serviceParameters, _ := json.Marshal(
            map[string]interface{}{
                "ossRegionId":  "ap-southeast-1",  // region where the bucket is located
                "ossBucketName": "bucket001",       // your OSS bucket name
                "ossObjectName": "image/001.jpg",   // object path in the bucket
                "dataId":        uuid.New().String(),
            },
        )
        imageModerationRequest := &green20220302.ImageModerationRequest{
            Service:           tea.String("baselineCheck_global"),
            ServiceParameters: tea.String(string(serviceParameters)),
        }
    
        return client.ImageModerationWithOptions(imageModerationRequest, runtime)
    }
    
    func main() {
        accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
        accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
        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
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == http.StatusOK {
                if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                    result := body.Data.Result
                    for i := 0; i < len(result); i++ {
                        fmt.Println("label:" + tea.StringValue(result[i].Label))
                        fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                    }
                } else {
                    fmt.Println("Moderation failed. code:", body.Code)
                }
            } else {
                fmt.Println("Request failed. status:", statusCode, "error:", _err)
            }
        }
    }

Node.js SDK

Source code: Node.js SDK on npm

Detect publicly accessible images

  1. Install the SDK:

    npm install @alicloud/green20220302@2.2.10
  2. Call the API:

    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 connection establishment and improve detection performance.
        var client = new RPCClient({
    				/**
             * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
             * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
             * Common ways to get environment variables:
             * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
             * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
             */
            accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable',
            accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable',
            // Modify the region and endpoint as needed.
            endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
            apiVersion: '2022-03-02',
            // Set the HTTP proxy.
            // httpProxy: "http://xx.xx.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
        });
    
        // Create an API request and set parameters.
        var params = {
            // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck_global
            "Service": "baselineCheck_global",
            // OSS information of the image to be detected.
            "ServiceParameters": JSON.stringify({
                // The region where the bucket of the file to be detected is located. Example: ap-southeast-1
                "ossRegionId": "ap-southeast-1",
                // The name of the bucket where the file to be detected is located. Example: bucket001
                "ossBucketName": "bucket001",
                // The file to be detected. Example: image/001.jpg
                "ossObjectName": "image/001.jpg",
                // A unique identifier for the data.
                "dataId": uuidv4()
            })
        }
    
        var requestOption = {
            method: 'POST',
            formatParams: false,
        };
    
        try {
            // Call the API operation to get the detection results.
            var response = await client.request('ImageModeration', params, requestOption)
            return response;
        } catch (err) {
            console.log(err);
        }
    }
    
    main().then(function (response) {
        console.log(JSON.stringify(response))
    });

Detect local images

  1. Install both dependencies:

    npm install @alicloud/green20220302@2.2.10
    npm install ali-oss --save
  2. Call the API:

    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;
    // File upload token.
    var tokenDic = new Array();
    // Client for file uploads.
    var ossClient;
    
    // Create a client for file uploads.
    function createClient(accessKeyId, accessKeySecret, endpoint) {
        return new RPCClient({
            accessKeyId: accessKeyId,
            accessKeySecret: accessKeySecret,
            endpoint: endpoint,
            apiVersion: '2022-03-02',
            // Set the HTTP proxy.
            // httpProxy: "http://xx.xx.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
        });
    }
    
    // Create a client for file uploads.
    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 connection establishment and improve detection performance.
        var client = createClient(accessKeyId, accessKeySecret, endpoint);
        var requestOption = {
            method: 'POST',
            formatParams: false,
        };
        // The full path of the local file, for example, D:\\localPath\\exampleFile.png.
        var filePath = 'D:\\localPath\\exampleFile.png';
    
        // Get the file upload token.
        if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
            var tokenResponse = await client.request('DescribeUploadToken', '', requestOption)
            tokenDic[endpoint] = tokenResponse.Data;
        }
    
        // Get the client for file uploads.
        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 detection API request and set parameters.
        var params = {
            // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. 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 get the detection results.
        return await client.request('ImageModeration', params, requestOption);
    }
    
    
    
    function main() {
    	/**
        * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
        * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
        * Common ways to get environment variables:
        * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
        * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        */
        const accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
        const accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
        // Modify the region and endpoint as needed.
        var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com"
    
        try {
            // Call the API operation to get the detection results.
            invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
                    console.log(JSON.stringify(response))
            })
        } catch (err) {
            console.log(err);
        }
    }
    
    main();

Detect OSS images

  1. Grant Content Moderation access to your OSS bucket: log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  2. Install the SDK:

    npm install @alicloud/green20220302@2.2.10
  3. Call the API:

    const RPCClient = require("@alicloud/pop-core");
    const { v4: uuidv4 } = require('uuid');
    
    async function main() {
        var client = new RPCClient({
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
            endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
            apiVersion: '2022-03-02',
        });
    
        var params = {
            "Service": "baselineCheck_global",
            "ServiceParameters": JSON.stringify({
                "ossRegionId": "ap-southeast-1",  // region where the bucket is located
                "ossBucketName": "bucket001",      // your OSS bucket name
                "ossObjectName": "image/001.jpg",  // object path in the bucket
                "dataId": uuidv4()
            })
        };
    
        var requestOption = { method: 'POST', formatParams: false };
    
        try {
            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

Source code: C# SDK on NuGet

Detect publicly accessible images

  1. Install the SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  2. Call the API:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageModerationAutoRoute
        {
            public static void Main(string[] args)
            {
                // Read credentials from environment variables — do not hardcode them.
                string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                // Change the endpoint to match your region.
                string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
    
                // Reuse the client across requests.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                // Set the service code configured in the AI Guardrails console.
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");  // public URL
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
    
                try
                {
                    Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
                    Console.WriteLine(response.Body.RequestId);
                    Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }
            }
    
            public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
            {
                AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    AccessKeyId = accessKeyId,
                    AccessKeySecret = accessKeySecret,
                    // Optional: set HTTP/HTTPS proxy if needed
                    // HttpProxy = "http://10.10.xx.xx:xxxx",
                    // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                    Endpoint = endpoint,
                };
                return new Client(config);
            }
        }
    }

Detect local images

Install the Content Moderation SDK and the OSS SDK:

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

For the OSS SDK, install via NuGet in Visual Studio:

  1. Open Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

  2. Search for aliyun.oss.sdk.

  3. Select Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .NET Core) and click Install.

Then call the API:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.OSS;

namespace AlibabaCloud.SDK.Green20220302
{
    public class ImageModerationAutoRoute
    {
        // Cache upload tokens by endpoint.
        public static Dictionary<string, Models.DescribeUploadTokenResponse> tokenDic =
            new Dictionary<string, Models.DescribeUploadTokenResponse>();

        public static OssClient ossClient = null;

        // Set to true when running in a VPC environment.
        public static bool isVPC = false;

        public static void Main(string[] args)
        {
            string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
            string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            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));
        }

        public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret,
                Endpoint = endpoint,
            };
            return new Client(config);
        }

        private static OssClient getOssClient(Models.DescribeUploadTokenResponse tokenResponse, bool isVPC)
        {
            var tokenData = tokenResponse.Body.Data;
            return isVPC
                ? new OssClient(tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken)
                : new OssClient(tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken);
        }

        public static string uploadFile(string filePath, Models.DescribeUploadTokenResponse tokenResponse)
        {
            ossClient = getOssClient(tokenResponse, isVPC);
            var tokenData = tokenResponse.Body.Data;
            string objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1);
            ossClient.PutObject(tokenData.BucketName, objectName, filePath);
            return objectName;
        }

        public static Models.ImageModerationResponse invoke(string accessKeyId, string accessKeySecret, string endpoint)
        {
            // Reuse the client across requests.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();

            // Replace with the actual path to your local file.
            string filePath = "D:\\localPath\\exampleFile.png";

            try
            {
                // Fetch and cache the upload token; refresh it when it expires.
                if (!tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds())
                {
                    tokenDic[endpoint] = client.DescribeUploadToken();
                }

                string objectName = uploadFile(filePath, tokenDic[endpoint]);

                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                task.Add("ossObjectName", objectName);
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);

                return client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
                return null;
            }
        }
    }
}

Detect OSS images

  1. Grant Content Moderation access to your OSS bucket: log on with your Alibaba Cloud account (root account) and go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.

  2. Install the SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  3. Call the API:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class OssScanDemo
        {
            public static void Main(string[] args)
            {
                string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
    
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("ossRegionId", "ap-southeast-1");  // region where the bucket is located
                task.Add("ossBucketName", "bucket001");      // your OSS bucket name
                task.Add("ossObjectName", "image/001.jpg");  // object path in the bucket
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
    
                try
                {
                    Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
                    Console.WriteLine(response.Body.RequestId);
                    Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }
            }
    
            public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
            {
                AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    AccessKeyId = accessKeyId,
                    AccessKeySecret = accessKeySecret,
                    Endpoint = endpoint,
                };
                return new Client(config);
            }
        }
    }

Native HTTPS calls

Use native HTTPS calls only when an SDK is not suitable for your environment:

  • Your app has strict size constraints on client dependencies.

  • You depend on specific library versions that cannot be upgraded.

With native HTTPS, you must manually construct the request URL, compute the HMAC-SHA1 signature, and assemble all request parameters.

Endpoint and protocol

  • Endpoint: https://green-cip.{region}.aliyuncs.com

  • Protocol: HTTPS

  • Method: POST

Common request parameters

Every request requires the following parameters:

ParameterTypeRequiredDescription
FormatStringYesResponse format: JSON (default) or XML
VersionStringYesAPI version in YYYY-MM-DD format. Value: 2022-03-02
AccessKeyIdStringYesYour AccessKey ID
SignatureStringYesHMAC-SHA1 signature string
SignatureMethodStringYesSignature algorithm: HMAC-SHA1
TimestampStringYesRequest time in ISO 8601 UTC format: yyyy-MM-ddTHH:mm:ssZ
SignatureVersionStringYesSignature algorithm version: 1.0
SignatureNonceStringYesUnique random number to prevent replay attacks; use a different value for each request
ActionStringYesAPI to call: ImageModeration (synchronous), ImageModerationAsync (asynchronous)

Common response parameters

Every response includes RequestId regardless of whether the call succeeds. The Data.Result array contains Label and Confidence fields. See the response format and field descriptions in the SDK section above.

Request example

The following example calls the synchronous baseline detection API:

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"}

Compute the signature

Image Moderation 2.0 uses HMAC-SHA1 to authenticate every request.

Step 1: Build the canonicalized query string

  1. Sort all request parameters alphabetically by parameter name (excluding Signature).

  2. URL-encode each parameter name and value using UTF-8 and these rules:

    • Do not encode: A–Z, a–z, 0–9, hyphen (-), underscore (_), period (.), tilde (~)

    • Encode other characters as %XY (hexadecimal ASCII)

    • Encode spaces as %20, not +; encode * as %2A; replace %7E with ~

    • Encode extended UTF-8 characters as %XY%ZA…

    Standard URL encoding libraries (such as java.net.URLEncoder) use the application/x-www-form-urlencoded MIME type rules. After encoding, replace + with %20, * with %2A, and %7E with ~.
  3. Connect each encoded name–value pair with =.

  4. Connect all pairs in alphabetical order with & to get the canonicalized query string.

Step 2: Build the string to sign

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

Where percentEncode("/") is %2F, and HTTPMethod is POST.

Step 3: Compute the HMAC-SHA1 value

As defined in RFC 2104, compute the HMAC-SHA1 hash of StringToSign. The signing key is your AccessKey secret followed by & (ASCII 38).

Step 4: Encode the result

Base64-encode the HMAC-SHA1 value to get the Signature string.

Step 5: Add the signature to the request

Append Signature as a URL-encoded query parameter using RFC 3986 encoding rules.

What's next