Image Moderation Enhanced Edition SDK and integration guide

更新时间:
复制 MD 格式

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 ServiceEnhanced Edition 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 detailsYou can also purchase usage-based resource plans. Resource plans offer tiered discounts compared to the pay-as-you-go billing method and are ideal for users with predictable and high usage volumes..

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

Region

Public endpoint

VPC endpoint

Supported service codes

China (Shanghai)

green-cip.cn-shanghai.aliyuncs.com

green-cip-vpc.cn-shanghai.aliyuncs.com

postImageCheckByVL, baselineCheckByVL, baselineCheck, baselineCheck_pro, tonalityImprove, aigcCheck, profilePhotoCheck, postImageCheck, advertisingCheck, liveStreamCheck, riskDetection, generalOcr, generalRecognition, faceDetect, faceDetect_pro

China (Chengdu)

green-cip.cn-chengdu.aliyuncs.com

None

China (Shenzhen)

green-cip.cn-shenzhen.aliyuncs.com

green-cip-vpc.cn-shenzhen.aliyuncs.com

China (Beijing)

green-cip.cn-beijing.aliyuncs.com

green-cip-vpc.cn-beijing.aliyuncs.com

China (Hangzhou)

green-cip.cn-hangzhou.aliyuncs.com

green-cip-vpc.cn-hangzhou.aliyuncs.com

Singapore

green-cip.ap-southeast-1.aliyuncs.com

green-cip-vpc.ap-southeast-1.aliyuncs.com

postImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global

China (Hong Kong)

green-cip.cn-hongkong.aliyuncs.com

green-cip-vpc.cn-hongkong.aliyuncs.com

postImageCheckByVL_cb, postImageCheckByVL_global

UK (London)

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

None

US (Virginia)

green-cip.us-east-1.aliyuncs.com

green-cip-vpc.us-east-1.aliyuncs.com

baselineCheck_global, aigcDetector_global

US (Silicon Valley)

green-cip.us-west-1.aliyuncs.com

None

Germany (Frankfurt)

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

green-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 source

What to do

Publicly accessible URL

Pass 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 bucket

Grant 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:

Field

Description

Label

The risk category detected (e.g., pornographic_adultContent, sexual_partialNudity). See Risk label descriptions for the full list.

Confidence

A 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>3.3.3</version>
    </dependency>
  2. 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 ImageUrlDemo {
    
        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 {
            // Reuse the client across requests to avoid repeated connection overhead.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // public URL
            serviceParameters.put("dataId", UUID.randomUUID().toString());
    
            ImageModerationRequest request = new ImageModerationRequest();
            // Set the service code configured in the AI Guardrails console. Example: baselineCheck_global
            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 {
            // Read credentials from environment variables — do not hardcode them.
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            // Change the endpoint to match your region.
            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() + ", msg=" + body.getMsg());
                }
            }
        }
    }
  3. Asynchronous API integration example

    Submit an asynchronous image detection task

    from alibabacloud_green20220302.client import Client
    from alibabacloud_green20220302 import models
    from alibabacloud_tea_openapi.models import Config
    import json
    import uuid
    
    config = Config(
        access_key_id='We recommend that you obtain the AccessKey ID from an environment variable',
        access_key_secret='We recommend that you obtain the AccessKey secret from an environment variable',
        # Connection timeout in milliseconds (ms).
        connect_timeout=3000,
        # Read timeout in milliseconds (ms).
        read_timeout=6000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    clt = Client(config)
    serviceParameters = {
        'imageUrl': 'https://www.aliyun.com/132.jpg',
        'dataId': str(uuid.uuid4()),
        'infoType': 'logoData'
    }
    ImageAsyncModerationRequest = models.ImageAsyncModerationRequest(
        # Detection type: baselineCheck for general baseline detection.
        service='baselineCheck',
        service_parameters=json.dumps(serviceParameters)
    )
    try:
        response = clt.image_async_moderation(ImageAsyncModerationRequest)
        if response.status_code == 200:
            body = response.body
            print('requestId:{}'.format(body.request_id))
            print('code:{}'.format(body.code))
            print('msg:{}'.format(body.msg))
            if body.code == 200:
                data = body.data
                print('reqId:{}'.format(data.req_id))
            else:
                print('response not success. code:{},msg:{}'.format(body.code, body.msg))
        else:
            print('response not success. status:{},result:{}'.format(response.status_code, response))
    
    except Exception as err:
        print(err)
    

    Obtain asynchronous image detection results

  4. Multi-service synchronous API integration 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)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("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.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                // Construct an image detection request.
                Models.ImageBatchModerationRequest imageBatchModerationRequest =
                    new Models.ImageBatchModerationRequest();
                // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
                  imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                Dictionary<string, object> task = new Dictionary<string, object>();
                // The region where the bucket of the image to be detected is located. Example: cn-shanghai
                task.Add("ossRegionId", "cn-shanghai");
                // The name of the bucket where the image to be detected is located. Example: bucket001
                task.Add("ossBucketName", "bucket001");
                // The name of the object of the image to be detected. Example: image/001.jpg
                task.Add("ossObjectName", "image/001.jpg");
                // The ID of the data to be detected.
                task.Add("dataId", Guid.NewGuid().ToString());
                imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                try
                {
                    // Call the API operation to get the detection results.
                    Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                        imageBatchModerationRequest,
                        runtimeOptions
                    );
                    // Automatic routing, switch region to cn-beijing.
                    if (
                        response is null
                        || response.Body is null
                        || AlibabaCloud.TeaUtil.Common.EqualNumber(
                            500,
                            AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                        )
                        || AlibabaCloud.TeaUtil.Common.EqualString(
                            "500",
                            Convert.ToString(response.Body.Code)
                        )
                    )
                    {
                        endpoint = "green-cip.cn-beijing.aliyuncs.com";
                        client = createClient(accessKeyId, accessKeySecret, endpoint);
                        response = client.ImageBatchModerationWithOptions(
                            imageBatchModerationRequest,
                            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 domain name to access.
                        Endpoint = endpoint,
                    };
                return new Client(config);
            }
        }
    }
  5. Asynchronous API integration example

    Submit an asynchronous image detection task

    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageAsyncModerationAutoRoute
        {
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                */
                String accessKeyId = "We recommend that you obtain the accessKeyId from an environment variable";
                String accessKeySecret = "We recommend that you obtain the accessKeySecret from an environment variable";
                // Modify the region and endpoint as needed.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.ImageAsyncModerationResponse response = invoke(
                    accessKeyId,
                    accessKeySecret,
                    endpoint
                );
                // Automatic routing, switch region to cn-beijing.
                if (
                    response is null
                    || response.Body is null
                    || AlibabaCloud.TeaUtil.Common.EqualNumber(
                        500,
                        AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                    )
                    || AlibabaCloud.TeaUtil.Common.EqualString(
                        "500",
                        Convert.ToString(response.Body.Code)
                    )
                )
                {
                    endpoint = "green-cip.cn-beijing.aliyuncs.com";
                    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);
            }
    
    
            // Submit a detection request.
            public static Models.ImageAsyncModerationResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                try
                {
    
                    // Construct a detection request.
                    Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                        new Models.ImageAsyncModerationRequest();
                    // Detection service. Example: baselineCheck
                      imageAsyncModerationRequest.Service = "baselineCheck";
                    Dictionary<string, object> task = new Dictionary<string, object>();
                    // Information to be detected.
                    task.Add("ossBucketName", "bucket1");
                    task.Add("ossObjectName", "aliyuntest.jpg");
                    task.Add("ossRegionId", "cn-shanghai");
                    // The ID of the data to be detected.
                    task.Add("dataId", Guid.NewGuid().ToString());
                    imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                    // Send the request.
                    Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                        imageAsyncModerationRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }

    Obtain asynchronous image detection results

    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class DescribeImageModerationResultAutoRoute
        {
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                */
                String accessKeyId = "We recommend that you obtain the accessKeyId from an environment variable";
                String accessKeySecret = "We recommend that you obtain the accessKeySecret from an environment variable";
                // Modify the region and endpoint as needed.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.DescribeImageModerationResultResponse 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);
            }
    
    
            // Submit a detection request.
            public static Models.DescribeImageModerationResultResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                try
                {
    
                    // Construct a detection request.
                    Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                        new Models.DescribeImageModerationResultRequest();
                      describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                    // Send the request.
                    Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                        describeImageModerationResultRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }
  6. Multi-service synchronous API integration 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 ImageBatchModerationAutoRoute
        {
            // File upload token.
            public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                new Dictionary<String, Models.DescribeUploadTokenResponse>();
    
            // Client for file uploads.
            public static OssClient ossClient = null;
    
            // Specifies whether the service is deployed in a VPC.
            public static Boolean isVPC = false;
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("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.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.ImageBatchModerationResponse response = invoke(
                    accessKeyId,
                    accessKeySecret,
                    endpoint
                );
                // Automatic routing, switch region to cn-beijing.
                if (
                    response is null
                    || response.Body is null
                    || AlibabaCloud.TeaUtil.Common.EqualNumber(
                        500,
                        AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                    )
                    || AlibabaCloud.TeaUtil.Common.EqualString(
                        "500",
                        Convert.ToString(response.Body.Code)
                    )
                )
                {
                    endpoint = "green-cip.cn-beijing.aliyuncs.com";
                    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 client for file uploads.
            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 a file.
            public static String uploadFile(
                String filePath,
                Models.DescribeUploadTokenResponse tokenResponse
            )
            {
                // Construct 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 detection request.
            public static Models.ImageBatchModerationResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is 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
                {
                    // Get 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]);
                    // Construct an image detection request.
                    Models.ImageBatchModerationRequest imageBatchModerationRequest =
                        new Models.ImageBatchModerationRequest();
                    // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
                      imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                    Dictionary<string, object> task = new Dictionary<string, object>();
                    // Information about the image to be detected.
                    task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                    task.Add("ossObjectName", objectName);
                    // The ID of the data to be detected.
                    task.Add("dataId", Guid.NewGuid().ToString());
                    imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                    // Call the API operation to get the detection results.
                    Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                        imageBatchModerationRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }
  7. Asynchronous API integration example

    Submit an asynchronous image detection task

    // This file is auto-generated, don't edit it. Thanks.
    
    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageAsyncModerationAutoRoute
        {
            // File upload token.
            public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                new Dictionary<String, Models.DescribeUploadTokenResponse>();
    
            // Client for file uploads.
            public static OssClient ossClient = null;
    
            // Specifies whether the service is deployed in a VPC.
            public static Boolean isVPC = false;
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("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.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.ImageAsyncModerationResponse response = invoke(
                    accessKeyId,
                    accessKeySecret,
                    endpoint
                );
                // Automatic routing, switch region to cn-beijing.
                if (
                    response is null
                    || response.Body is null
                    || AlibabaCloud.TeaUtil.Common.EqualNumber(
                        500,
                        AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                    )
                    || AlibabaCloud.TeaUtil.Common.EqualString(
                        "500",
                        Convert.ToString(response.Body.Code)
                    )
                )
                {
                    endpoint = "green-cip.cn-beijing.aliyuncs.com";
                    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 client for file uploads.
            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 a file.
            public static String uploadFile(
                String filePath,
                Models.DescribeUploadTokenResponse tokenResponse
            )
            {
                // Construct 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 detection request.
            public static Models.ImageAsyncModerationResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is 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.jpg.
                String filePath = "/Users/admin/test/image/1.jpg";
                try
                {
                    // Get 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]);
                    // Construct a detection request.
                    Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                        new Models.ImageAsyncModerationRequest();
                    // Detection service. Example: baselineCheck
                      imageAsyncModerationRequest.Service = "baselineCheck";
                    Dictionary<string, object> task = new Dictionary<string, object>();
                    // Information to be detected.
                    task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                    task.Add("ossObjectName", objectName);
                    // The ID of the data to be detected.
                    task.Add("dataId", Guid.NewGuid().ToString());
                    imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                    // Send the request.
                    Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                        imageAsyncModerationRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }

    Obtain asynchronous image detection results

    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class DescribeImageModerationResultAutoRoute
        {
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                */
                String accessKeyId = "We recommend that you obtain the accessKeyId from an environment variable";
                String accessKeySecret = "We recommend that you obtain the accessKeySecret from an environment variable";
                // Modify the region and endpoint as needed.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.DescribeImageModerationResultResponse 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);
            }
    
    
            // Submit a detection request.
            public static Models.DescribeImageModerationResultResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                try
                {
    
                    // Construct a detection request.
                    Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                        new Models.DescribeImageModerationResultRequest();
                      describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                    // Send the request.
                    Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                        describeImageModerationResultRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }
  8. Multi-service synchronous API integration example

    // This file is auto-generated, don't edit it. Thanks.
    
    using Newtonsoft.Json;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageBatchModerationAutoRoute
        {
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("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.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                // Construct an image detection request.
                Models.ImageBatchModerationRequest imageBatchModerationRequest =
                    new Models.ImageBatchModerationRequest();
                // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck 
                  imageBatchModerationRequest.Service = "baselineCheck,profilePhotoCheck";
                Dictionary<string, object> task = new Dictionary<string, object>();
                // The URL of the image to be detected, which must be publicly accessible.
                task.Add(
                    "imageUrl",
                    "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
                );
                // The ID of the data to be detected.
                task.Add("dataId", Guid.NewGuid().ToString());
                imageBatchModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
    
                try
                {
                    // Call the API operation to get the detection results.
                    Models.ImageBatchModerationResponse response = client.ImageBatchModerationWithOptions(
                        imageBatchModerationRequest,
                        runtimeOptions
                    );
                    // Automatic routing, switch region to cn-beijing.
                    if (
                        response is null
                        || response.Body is null
                        || AlibabaCloud.TeaUtil.Common.EqualNumber(
                            500,
                            AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                        )
                        || AlibabaCloud.TeaUtil.Common.EqualString(
                            "500",
                            Convert.ToString(response.Body.Code)
                        )
                    )
                    {
                        endpoint = "green-cip.cn-beijing.aliyuncs.com";
                        client = createClient(accessKeyId, accessKeySecret, endpoint);
                        response = client.ImageBatchModerationWithOptions(
                            imageBatchModerationRequest,
                            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 domain name to access.
                        Endpoint = endpoint,
                    };
                return new Client(config);
            }
        }
    }
  9. Multi-service synchronous API integration example

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                "service": "baselineCheck,profilePhotoCheck",
                "serviceParameters": JSON.stringify({
                // The region where the bucket of the file to be detected is located. Example: cn-shanghai
                "ossRegionId": "cn-shanghai",
                // 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()
                })
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  10. Asynchronous API integration example

    Submit an asynchronous image detection task

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                "service": "baselineCheck",
                "serviceParameters": JSON.stringify({
                 // The region where the bucket of the file to be detected is located. Example: cn-shanghai
                "ossRegionId": "cn-shanghai",
                // 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()
                })
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();

    Obtain asynchronous image detection results

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  11. Multi-service synchronous API integration example

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const { v4: uuidv4 } = require('uuid');
    const OSS = require('ali-oss');
    const Util = require('@alicloud/tea-util');
    const path = require("path");
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    
    // 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;
    var endpoint = 'green-cip.cn-shanghai.aliyuncs.com'
    var filePath = '/Users/admin/test/image/0873.jpg'
    var service = 'baselineCheck,profilePhotoCheck'
    
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: endpoint,
            });
            return new Green20220302.default(config);
        }
    
        // Create a client for file uploads.
        static 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'],
                });
            }
        }
    
        static async main() {
            const client = Client.createClient();
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            
            // Get the file upload token.
            if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) {
                var tokenResponse = await client.describeUploadTokenWithOptions(runtime)
                tokenDic[endpoint] = tokenResponse.body.data;
            }
    
            // Get the client for file uploads.
        this.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));
    
            // Construct a request object.
            const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                // Detection service.
                "service": service,
                // Link to be detected.
                "serviceParameters": JSON.stringify({
                    "ossBucketName": tokenDic[endpoint].bucketName,
                    "ossObjectName": objectName,
                })
                });
    
            try {
                // Send the request and get the response.
                const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  12. Asynchronous API integration example

    Submit an asynchronous image detection task

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const { v4: uuidv4 } = require('uuid');
    const OSS = require('ali-oss');
    const Util = require('@alicloud/tea-util');
    const path = require("path");
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    
    // 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;
    var endpoint = 'green-cip.cn-shanghai.aliyuncs.com'
    var filePath = '/Users/Documents/test/11.jpg'
    var service = 'baselineCheck'
    
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: endpoint,
            });
            return new Green20220302.default(config);
        }
    
        // Create a client for file uploads.
        static 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'],
                });
            }
        }
    
        static async main() {
            const client = Client.createClient();
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            
            // Get the file upload token.
            if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) {
                var tokenResponse = await client.describeUploadTokenWithOptions(runtime)
                tokenDic[endpoint] = tokenResponse.body.data;
            }
    
            // Get the client for file uploads.
        this.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));
    
            // Construct a request object.
            const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                // Detection service.
                "service": service,
                // Link to be detected.
                "serviceParameters": JSON.stringify({
                    "ossBucketName": tokenDic[endpoint].bucketName,
                    "ossObjectName": objectName,
                })
                });
    
            try {
                // Send the request and get the response.
                const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();

    Obtain asynchronous image detection results

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  13. Multi-service synchronous API integration example

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const imageBatchModerationRequest = new Green20220302.ImageBatchModerationRequest({
                "service": "baselineCheck,profilePhotoCheck",
                "serviceParameters": JSON.stringify({"imageurl":"http://www.aliyun.com/test.jpg"})
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  14. Multi-service synchronous API integration example

    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"
    )
    
    // Create a request client.
    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.ImageBatchModerationResponse, _err error) {
       client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
       if _err != nil {
          return nil, _err
       }
       runtime := &util.RuntimeOptions{}
       serviceParameters, _ := json.Marshal(
          map[string]interface{}{
    	 "ossRegionId": "cn-shanghai",
    	 // The name of the bucket where the image to be detected is located. Example: bucket001
    	 "ossBucketName":"bucket001",
    	 // The name of the object of the image to be detected. Example: image/001.jpg
    	 "ossObjectName":"image/001.jpg",
             // The ID of the data to be detected.
             "dataId": uuid.New(),
          },
       )
    
       ImageBatchModerationRequest := &green20220302.ImageBatchModerationRequest{
          Service:tea.String("baselineCheck,baselineCheck_pro"),
          ServiceParameters: tea.String(string(serviceParameters)),
       }
    
       return client.ImageBatchModerationWithOptions(ImageBatchModerationRequest, runtime)
    
    }
    
    func main() {
       var accessKeyId = tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable")
       var accessKeySecret = tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable")
       var endpoint = tea.String("green-cip.cn-shanghai.aliyuncs.com")
       response, _err := invoke(accessKeyId, accessKeySecret, endpoint)
       if _err != nil {
          return;
       }
       if response != nil {
          statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
          body := response.Body
          imageBatchModerationResponseData := body.Data
          fmt.Println("requestId:" + tea.StringValue(body.RequestId))
          if statusCode == 200 {
             fmt.Println("response success. response:" + body.String())
             if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                result := imageBatchModerationResponseData.Result
                fmt.Println("response dataId:" + tea.StringValue(imageBatchModerationResponseData.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))
          }
       }
    }
    
  15. Asynchronous API integration example

    Submit an asynchronous image detection task

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	green "github.com/alibabacloud-go/green-20220302/v3/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"),
    		AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"),
    		// The endpoint to access.
    		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
    		/**
    		 * Set a timeout period. The server-side full-link processing timeout is 10 seconds. Set the timeout accordingly.
    		 * If the ReadTimeout you set is less than the server processing time, a ReadTimeout exception will be thrown in the program.
    		 */
    		ConnectTimeout: tea.Int(3000),
    		ReadTimeout:    tea.Int(6000),
    	}
    	client, _err := green.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    
    	serviceParameters, _ := json.Marshal(
    		map[string]interface{}{
    		// The region where the bucket of the image to be detected is located. Example: cn-shanghai
    	    "ossRegionId": "cn-shanghai",
    	    // The name of the bucket where the image to be detected is located. Example: bucket001
    	    "ossBucketName":"bucket001",
    	    // The name of the object of the image to be detected. Example: image/001.jpg
    	    "ossObjectName":"image/001.jpg",
    	    // The ID of the data to be detected.
    	    "dataId":   uuid.New().String(),
    		},
    	)
    	request := green.ImageAsyncModerationRequest{
    		Service:           tea.String("baselineCheck"),
    		ServiceParameters: tea.String(string(serviceParameters)),
    	}
    	result, err := client.ImageAsyncModeration(&request)
    	if err != nil {
    		fmt.Print(err.Error())
    	}
    	fmt.Printf("response is %#v\n", result.Body)
    }
    

    Obtain asynchronous image detection results

    package main
    
    import (
    	"fmt"
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	green "github.com/alibabacloud-go/green-20220302/v3/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"),
    		AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"),
    		// The endpoint to access.
    		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
    		/**
    		 * Set a timeout period. The server-side full-link processing timeout is 10 seconds. Set the timeout accordingly.
    		 * If the ReadTimeout you set is less than the server processing time, a ReadTimeout exception will be thrown in the program.
    		 */
    		ConnectTimeout: tea.Int(3000),
    		ReadTimeout:    tea.Int(6000),
    	}
    	client, _err := green.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    
    	request := green.DescribeImageModerationResultRequest{
    		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
    	}
    	result, err := client.DescribeImageModerationResult(&request)
    	if err != nil {
    		fmt.Print(err.Error())
    	}
    	fmt.Printf("response is %#v\n", result.Body)
    }
  16. Multi-service synchronous API integration example

    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"
    )
    // File upload token.
    var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
    // Client for file uploads.
    var Bucket *oss.Bucket
    // Specifies whether the service is deployed in a VPC.
    var isVPC = false
    // Create a request client.
    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 as much as possible to avoid repeated connection establishment and improve detection performance.
    	return green20220302.NewClient(config);
    }
    
    // Create a client for file uploads.
    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 a 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.ImageBatchModerationResponse, _err error) {
    	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
    	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
    	if _err != nil {
    		return nil,_err
    	}
    	// Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
    	runtime := &util.RuntimeOptions{}
    	// The full path of the local file, for example, D:\localPath\exampleFile.png.
    	var filePath = "/Users/admin/test/image/0873.jpg"
    	// Get a temporary token for file upload.
    	tokenData,ok:=TokenMap[endpoint];
    	if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
    		// Get 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 detection request.
    	serviceParameters, _ := json.Marshal(
    		map[string]interface{}{
    			"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
    			"ossObjectName": objectName,
    			"dataId":   uuid.New().String(),
    		},
    	)
    	imageBatchModerationRequest := &green20220302.ImageBatchModerationRequest{
    		// Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
    		Service:           tea.String("baselineCheck,profilePhotoCheck"),
    		ServiceParameters: tea.String(string(serviceParameters)),
    	}
    
    	return client.ImageBatchModerationWithOptions(imageBatchModerationRequest, runtime)
    
    }
    
    func 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: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
    	 */
    	var accessKeyId= "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"
    	var 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 = "green-cip.cn-shanghai.aliyuncs.com"
    	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
    
    	flag := false
    	if _err != nil {
    		var err = &tea.SDKError{}
    		if _t, ok := _err.(*tea.SDKError); ok {
    			err = _t
    			if *err.StatusCode == 500 {
    				flag = true
    			}
    		}
    	}
    	if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
    		flag = true
    	}
    	// Automatic routing, switch region to cn-beijing.
    	if flag {
    		endpoint = "green-cip.cn-beijing.aliyuncs.com";
    		response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
    	}
    
    	if response != nil {
    		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
    		body := response.Body
    		imageBatchModerationResponseData := 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 := imageBatchModerationResponseData.Result
    				fmt.Println("response dataId:" + tea.StringValue(imageBatchModerationResponseData.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))
    		}
    	}
    }
    
  17. Asynchronous API integration example

    Submit an asynchronous image detection task

    Obtain asynchronous image detection results

    package main
    
    import (
    	"fmt"
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	green "github.com/alibabacloud-go/green-20220302/v3/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"),
    		AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"),
    		// The endpoint to access.
    		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
    		/**
    		 * Set a timeout period. The server-side full-link processing timeout is 10 seconds. Set the timeout accordingly.
    		 * If the ReadTimeout you set is less than the server processing time, a ReadTimeout exception will be thrown in the program.
    		 */
    		ConnectTimeout: tea.Int(3000),
    		ReadTimeout:    tea.Int(6000),
    	}
    	client, _err := green.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    
    	request := green.DescribeImageModerationResultRequest{
    		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
    	}
    	result, err := client.DescribeImageModerationResult(&request)
    	if err != nil {
    		fmt.Print(err.Error())
    	}
    	fmt.Printf("response is %#v\n", result.Body)
    }
  18. Multi-service synchronous API integration example

  19. Multi-service synchronous API integration example

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return ImageBatchModerationResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageBatchModerationResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
      	$request = new ImageBatchModerationRequest();
        $serviceParameters = array(
              // The file to be detected. Example: image/001.jpg
            'ossObjectName' => 'image/001.jpg',
            // The region where the bucket of the file to be detected is located. Example: cn-shanghai
            'ossRegionId' => 'cn-shanghai',
              // The name of the bucket where the file to be detected is located. Example: bucket001
            'ossBucketName' => 'bucket001',
            'dataId' => uniqid());
      	// Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
      	// For more information about supported services, see: https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
      	$request->service = "baselineCheck,profilePhotoCheck";
        $request->serviceParameters = json_encode($serviceParameters);
        // Submit for detection.
        return $client->imageBatchModerationWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.aliyuncs.com";
    
    try {
        $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
        // Automatic routing.
        if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
            // Switch the region to cn-beijing.
            $endpoint = "green-cip.cn-beijing.aliyuncs.com";
            $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());
    }
  20. Asynchronous API integration example

    Submit an asynchronous image detection task

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return ImageAsyncModerationResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageAsyncModerationResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
        $request = new ImageAsyncModerationRequest();
        $serviceParameters = array(
          	// The file to be detected. Example: image/001.jpg
            'ossObjectName' => 'image/001.jpg',
            // The region where the bucket of the file to be detected is located. Example: cn-shanghai
            'ossRegionId' => 'cn-shanghai',
          	// The name of the bucket where the file to be detected is located. Example: bucket001
            'ossBucketName' => 'bucket001',
            );
        // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
        $request->service = "baselineCheck";
        $request->serviceParameters = json_encode($serviceParameters);
        // Submit for detection.
        return $client->imageAsyncModerationWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.aliyuncs.com";
    
    try {
        $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
        // Automatic routing.
        if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
            // Switch the region to cn-beijing.
            $endpoint = "green-cip.cn-beijing.aliyuncs.com";
            $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());
    }

    Obtain asynchronous image detection results

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return DescribeImageModerationResultResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
        $request = new DescribeImageModerationResultRequest();
    
        $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
        // Submit for detection.
        return $client->describeImageModerationResultWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.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());
    }
  21. Multi-service synchronous API integration example

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageBatchModerationResponse;
    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\ImageBatchModerationRequest;
    use OSS\OssClient;
    
    // Specifies whether the service is deployed in a VPC.
    $isVPC = false;
    // File upload token.
    $tokenArray = array();
    // 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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Create a client for file uploads.
     * @param $tokenData
     * @return void
     */
    function create_upload_client($tokenData): void
    {
    
        global $isVPC;
        global $ossClient;
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection 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 a file.
     * @param $fileName
     * @param $tokenData
     * @return string
     * @throws \OSS\Core\OssException
     */
    function upload_file($filePath, $tokenData): string
    {
        global $ossClient;
        // Initialize OssClient.
        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 detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return ImageBatchModerationResponse
     * @throws \OSS\Core\OssException
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageBatchModerationResponse
    {
        global $tokenArray;
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection 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, for example, D:\\localPath\\exampleFile.png.
        $filePath = "D:\\localPath\\exampleFile.png";
    
        // Get the 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 detection parameters.
        $request = new ImageBatchModerationRequest();
        // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
        // For more information about supported services, see: https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
          $request->service = "baselineCheck,profilePhotoCheck";
        // OSS information of the image to be detected.
        $serviceParameters = array(
            'ossObjectName' => $objectName,
            'ossBucketName' => $tokenArray[$endpoint]->bucketName,
            'dataId' => uniqid());
        $request->serviceParameters = json_encode($serviceParameters);
        // Submit for detection.
        return $client->imageBatchModerationWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.aliyuncs.com";
    
    try {
        $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
        // Automatic routing.
        if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
            // Switch the region to cn-beijing.
            $endpoint = "green-cip.cn-beijing.aliyuncs.com";
            $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());
    }
  22. Asynchronous API integration example

    Submit an asynchronous image detection task

    Obtain asynchronous image detection results

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return DescribeImageModerationResultResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
        $request = new DescribeImageModerationResultRequest();
    
        $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
        // Submit for detection.
        return $client->describeImageModerationResultWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.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());
    }
  23. Multi-service synchronous API integration example

  24. Asynchronous API integration example

    Submit an asynchronous image detection task

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                // accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                // accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const imageAsyncModerationRequest = new Green20220302.ImageAsyncModerationRequest({
                "service": "baselineCheck",
                "serviceParameters": JSON.stringify({"imageurl":"http://www.aliyun.com/test.jpg"})
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();

    Obtain asynchronous image detection results

    const Green20220302 = require('@alicloud/green20220302');
    const OpenApi = require('@alicloud/openapi-client');
    const Util = require('@alicloud/tea-util');
    // Note: Reuse the instantiated client as much as possible to improve detection performance. Avoid repeated connection establishment.
    // Leaking project code may lead to AccessKey leaks and threaten the security of all resources in your account. The following code example is for reference only.
    class Client {
        static createClient() {
            const config = new OpenApi.Config({
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_ID is set in your code's runtime environment.
                accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                // Required. Make sure the environment variable ALIBABA_CLOUD_ACCESS_KEY_SECRET is set in your code's runtime environment.
                accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
            });
            return new Green20220302.default(config);
        }
    
        static async main() {
            const client = Client.createClient();
            // Construct a request object.
            const describeImageModerationResultRequest = new Green20220302.DescribeImageModerationResultRequest({
                "reqId": "5B61EF1B-FF90-5264-8083-9FA75E955E01",
            });
            // Create a runtime configuration object.
            const runtime = new Util.RuntimeOptions();
            try {
                // Send the request and get the response.
                const response = await client.describeImageModerationResultWithOptions(describeImageModerationResultRequest, runtime);
                console.log(JSON.stringify(response.body));
            } catch (error) {
                // This is for printing purposes only. Handle exceptions with caution and do not ignore them in your project.
                // Error message
                console.log('Error occurred:', error.message);
            }
        }
    }
    
    Client.main();
  25. Multi-service synchronous API integration 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
    
    
    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 = {
            # The region where the bucket of the file to be detected is located. Example: cn-shanghai
            'ossRegionId': 'cn-shanghai',
            # 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',
            'dataId': str(uuid.uuid1())
        }
        image_batchtion_request = models.ImageBatchModerationRequest(
            'baselineCheck,baselineCheck_pro',
            json.dumps(service_parameters)
    
        )
    
        try:
            return client.image_batch_moderation_with_options(image_batchtion_request, runtime)
        except Exception as err:
            print(err)
    
    
    if __name__ == '__main__':
        access_key_id = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
        access_key_secret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
        print('response:{}', response)
    
        if response is not None:
            if response.status_code == 200:
                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))
    
  26. Asynchronous API integration example

    Submit an asynchronous image detection task

    from alibabacloud_green20220302.client import Client
    from alibabacloud_green20220302 import models
    from alibabacloud_tea_openapi.models import Config
    import json
    import uuid
    
    config = Config(
        access_key_id='We recommend that you obtain the AccessKey ID from an environment variable',
        access_key_secret='We recommend that you obtain the AccessKey secret from an environment variable',
        # Connection timeout in milliseconds (ms).
        connect_timeout=3000,
        # Read timeout in milliseconds (ms).
        read_timeout=6000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    clt = Client(config)
    serviceParameters = {
        'ossBucketName': 'bucket_01',
        'ossObjectName': '2022023/04/24/test.jpg',
        'ossRegionId': 'cn-shanghai',
        'dataId': str(uuid.uuid4()),
        'infoType': 'logoData'
    }
    ImageAsyncModerationRequest = models.ImageAsyncModerationRequest(
        # Detection type: baselineCheck for general baseline detection.
        service='baselineCheck',
        service_parameters=json.dumps(serviceParameters)
    )
    try:
        response = clt.image_async_moderation(ImageAsyncModerationRequest)
        if response.status_code == 200:
            body = response.body
            print('requestId:{}'.format(body.request_id))
            print('code:{}'.format(body.code))
            print('msg:{}'.format(body.msg))
            if body.code == 200:
                data = body.data
                print('reqId:{}'.format(data.req_id))
            else:
                print('response not success. code:{},msg:{}'.format(body.code, body.msg))
        else:
            print('response not success. status:{},result:{}'.format(response.status_code, response))
    
    except Exception as err:
        print(err)
    

    Obtain asynchronous image detection results

    from alibabacloud_green20220302.client import Client
    from alibabacloud_green20220302 import models
    from alibabacloud_tea_openapi.models import Config
    
    config = Config(
        access_key_id='We recommend that you obtain the AccessKey ID from an environment variable',
        access_key_secret='We recommend that you obtain the AccessKey secret from an environment variable',
        # Connection timeout in milliseconds (ms).
        connect_timeout=3000,
        # Read timeout in milliseconds (ms).
        read_timeout=6000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    clt = Client(config)
    
    DescribeImageModerationResultRequest = models.DescribeImageModerationResultRequest(
        req_id='64C35F30-FFB3-5312-96E1-04DC8D2AE19D'
    )
    try:
        response = clt.describe_image_moderation_result(DescribeImageModerationResultRequest)
        if response.status_code == 200:
            body = response.body
            print('requestId:{}'.format(body.request_id))
            print('code:{}'.format(body.code))
            print('msg:{}'.format(body.msg))
            if body.code == 200:
                data = body.data
                print(data.to_map())
                print('dataId:{}'.format(data.data_id))
                print('riskLevel:{}'.format(data.risk_level))
                result = data.result[0]
                print(result.to_map())
            else:
                print('response not success. code:{},msg:{}'.format(body.code, body.msg))
        else:
            print('response not success. status:{},result:{}'.format(response.status_code, response))
    
    except Exception as err:
        print(err)
    
  27. Multi-service synchronous API integration example

    from alibabacloud_green20220302.client import Client
    from alibabacloud_green20220302 import models
    from alibabacloud_tea_openapi.models import Config
    from alibabacloud_tea_util.client import Client as UtilClient
    from alibabacloud_tea_util import models as util_models
    import json
    import uuid
    import oss2
    import time
    
    # Specifies whether the service is deployed in a VPC.
    is_vpc = False
    # File upload token: endpoint->token
    token_dict = dict()
    # Client for file uploads.
    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 client for file uploads.
    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: Reuse the instantiated bucket as much as possible to avoid repeated connection establishment and improve detection performance.
        bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
    
    
    # Upload a file.
    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: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        client = create_client(access_key_id, access_key_secret, endpoint)
        # Create a RuntimeObject instance and set runtime parameters.
        runtime = util_models.RuntimeOptions()
    
        # The full path of the local file, for example, D:\localPath\exampleFile.png.
        file_path = 'D:\\localPath\\exampleFile.png'
    
        # Get the file upload token.
        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 detection parameters.
        service_parameters = {
            # The name of the bucket where the file to be detected is located.
            'ossBucketName': upload_token.bucket_name,
            # The file to be detected.
            'ossObjectName': object_name,
            # A unique identifier for the data.
            'dataId': str(uuid.uuid1())
        }
    
        image_batch_moderation_request = models.ImageBatchModerationRequest(
            # Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
            service='baselineCheck,aigcCheck',
            service_parameters=json.dumps(service_parameters)
        )
    
        try:
            return client.image_batch_moderation_with_options(image_batch_moderation_request, runtime)
        except Exception as err:
            print(err)
    
    
    if __name__ == '__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: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        access_key_id = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
        access_key_secret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
        # Modify the region and endpoint as needed.
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
        # Automatic routing.
        if response is not None:
            if UtilClient.equal_number(500,
                                       response.status_code) or (response.body is not None and 200 != response.body.code):
                # Switch the region to cn-beijing.
                response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
    
            if response.status_code == 200:
                # The call was successful.
                # Get the moderation results.
                result = response.body
                print('requestId:{}'.format(result.request_id))
                print('code:{}'.format(result.code))
                print('msg:{}'.format(result.msg))
                if result.code == 200:
                    data = result.data
                    print('riskLevel:{}'.format(data.risk_level))
                    print(data.to_map())
            else:
                print('response not success. status:{} ,result:{}'.format(response.status_code, response))
    
  28. Asynchronous API integration example

    Submit an asynchronous image detection task

    Obtain asynchronous image detection results

    from alibabacloud_green20220302.client import Client
    from alibabacloud_green20220302 import models
    from alibabacloud_tea_openapi.models import Config
    
    config = Config(
        access_key_id='We recommend that you obtain the AccessKey ID from an environment variable',
        access_key_secret='We recommend that you obtain the AccessKey secret from an environment variable',
        # Connection timeout in milliseconds (ms).
        connect_timeout=3000,
        # Read timeout in milliseconds (ms).
        read_timeout=6000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    clt = Client(config)
    
    DescribeImageModerationResultRequest = models.DescribeImageModerationResultRequest(
        req_id='64C35F30-FFB3-5312-96E1-04DC8D2AE19D'
    )
    try:
        response = clt.describe_image_moderation_result(DescribeImageModerationResultRequest)
        if response.status_code == 200:
            body = response.body
            print('requestId:{}'.format(body.request_id))
            print('code:{}'.format(body.code))
            print('msg:{}'.format(body.msg))
            if body.code == 200:
                data = body.data
                print(data.to_map())
                print('dataId:{}'.format(data.data_id))
                print('riskLevel:{}'.format(data.risk_level))
                result = data.result[0]
                print(result.to_map())
            else:
                print('response not success. code:{},msg:{}'.format(body.code, body.msg))
        else:
            print('response not success. status:{},result:{}'.format(response.status_code, response))
    
    except Exception as err:
        print(err)
    
  29. Multi-service synchronous API integration 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
    
    
    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 = {
            'imageUrl': 'http://www.aliyun.com/2c06373cj00s8j82k004ld000zk01bfc.jpg',
            'dataId': str(uuid.uuid1())
        }
        image_batchtion_request = models.ImageBatchModerationRequest(
            'baselineCheck,baselineCheck_pro',
            json.dumps(service_parameters)
    
        )
    
        try:
            return client.image_batch_moderation_with_options(image_batchtion_request, runtime)
        except Exception as err:
            print(err)
    
    
    if __name__ == '__main__':
        access_key_id = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
        access_key_secret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
        print('response:{}', response)
    
        if response is not None:
            if response.status_code == 200:
                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))
    
  30. Asynchronous API integration example

    Submit an asynchronous image detection task

    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageAsyncModerationAutoRoute
        {
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                */
                String accessKeyId = "We recommend that you obtain the accessKeyId from an environment variable";
                String accessKeySecret = "We recommend that you obtain the accessKeySecret from an environment variable";
                // Modify the region and endpoint as needed.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.ImageAsyncModerationResponse response = invoke(
                    accessKeyId,
                    accessKeySecret,
                    endpoint
                );
                // Automatic routing, switch region to cn-beijing.
                if (
                    response is null
                    || response.Body is null
                    || AlibabaCloud.TeaUtil.Common.EqualNumber(
                        500,
                        AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                    )
                    || AlibabaCloud.TeaUtil.Common.EqualString(
                        "500",
                        Convert.ToString(response.Body.Code)
                    )
                )
                {
                    endpoint = "green-cip.cn-beijing.aliyuncs.com";
                    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);
            }
    
    
            // Submit a detection request.
            public static Models.ImageAsyncModerationResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                try
                {
    
                    // Construct a detection request.
                    Models.ImageAsyncModerationRequest imageAsyncModerationRequest =
                        new Models.ImageAsyncModerationRequest();
                    // Detection service. Example: baselineCheck
                      imageAsyncModerationRequest.Service = "baselineCheck";
                    Dictionary<string, object> task = new Dictionary<string, object>();
                    // Information to be detected.
                    task.Add("imageUrl", "https://www.aliyun.com/a.jpg");
                    // The ID of the data to be detected.
                    task.Add("dataId", Guid.NewGuid().ToString());
                    imageAsyncModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                    // Send the request.
                    Models.ImageAsyncModerationResponse response = client.ImageAsyncModerationWithOptions(
                        imageAsyncModerationRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }

    Obtain asynchronous image detection results

    using System;
    using Newtonsoft.Json;
    using Aliyun.OSS;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class DescribeImageModerationResultAutoRoute
        {
    
            public static void Main(string[] args)
            {
                /**
                * 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: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                */
                String accessKeyId = "We recommend that you obtain the accessKeyId from an environment variable";
                String accessKeySecret = "We recommend that you obtain the accessKeySecret from an environment variable";
                // Modify the region and endpoint as needed.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.DescribeImageModerationResultResponse 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);
            }
    
    
            // Submit a detection request.
            public static Models.DescribeImageModerationResultResponse invoke(
                String accessKeyId,
                String accessKeySecret,
                String endpoint
            )
            {
                // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                    new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                try
                {
    
                    // Construct a detection request.
                    Models.DescribeImageModerationResultRequest describeImageModerationResultRequest =
                        new Models.DescribeImageModerationResultRequest();
                      describeImageModerationResultRequest.ReqId = "ABCD1234-1234-1234-1234-123****";
                    // Send the request.
                    Models.DescribeImageModerationResultResponse response = client.DescribeImageModerationResultWithOptions(
                        describeImageModerationResultRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }
  31. Asynchronous API integration 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 of an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user for API calls or 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 the resources in your account may be exposed to security risks.
                * The following code shows how to obtain an 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 = "Retrieve the AccessKey ID of a RAM user from an environment variable.";
                String accessKeySecret = "Retrieve the AccessKey secret of a RAM user from an environment variable.";
                // The region and endpoint. Modify the values based on your actual business needs.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                // Note: We recommend that you reuse the client instance to avoid repeated connection establishment and improve detection performance.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
    
                // Set runtime parameters. The settings are valid only for requests that use the RuntimeOptions 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 of a rule that you configured for the Image Moderation (Enhanced) service in the AI Guardrails console. Example: baselineCheck
              	//For more information about supported services, see: https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff  
              	imageModerationRequest.Service = "baselineCheck";
                Dictionary<string, object> task = new Dictionary<string, object>();
                //The URL of the image to be moderated. The URL must be accessible over the public network.
                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
                    );
                    //Automatic routing. Switch the region to cn-beijing.
                    if (
                        response is null
                        || response.Body is null
                        || AlibabaCloud.TeaUtil.Common.EqualNumber(
                            500,
                            AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                        )
                        || AlibabaCloud.TeaUtil.Common.EqualString(
                            "500",
                            Convert.ToString(response.Body.Code)
                        )
                    )
                    {
                        endpoint = "green-cip.cn-beijing.aliyuncs.com";
                        client = createClient(accessKeyId, accessKeySecret, endpoint);
                        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.
            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 to be accessed.
                        Endpoint = endpoint,
                    };
                return new Client(config);
            }
        }
    }
    // 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 token for file upload.
            public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                new Dictionary<String, Models.DescribeUploadTokenResponse>();
    
            // The client for file upload.
            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 Alibaba Cloud account's AccessKey pair has full access to 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 an AccessKey pair in the project code. Otherwise, the AccessKey pair may be leaked and all resources in your account may be exposed to potential security risks.
                * You can obtain the environment variables using one of the following methods:
                * 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 based on your actual requirements.
                String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                Models.ImageModerationResponse response = invoke(
                    accessKeyId,
                    accessKeySecret,
                    endpoint
                );
                // Automatically switch to the cn-beijing region.
                if (
                    response is null
                    || response.Body is null
                    || AlibabaCloud.TeaUtil.Common.EqualNumber(
                        500,
                        AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                    )
                    || AlibabaCloud.TeaUtil.Common.EqualString(
                        "500",
                        Convert.ToString(response.Body.Code)
                    )
                )
                {
                    endpoint = "green-cip.cn-beijing.aliyuncs.com";
                    response = invoke(accessKeyId, accessKeySecret, endpoint);
                    ;
                }
    
                Console.WriteLine(response.Body.RequestId);
                Console.WriteLine(JsonConvert.SerializeObject(response.Body));
            }
    
            // 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 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 of the service.
                        Endpoint = endpoint,
                    };
                return new Client(config);
            }
    
            // Create a client for file upload.
            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 a 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: We recommend that you reuse the client instance to avoid repeatedly creating connections and to improve moderation 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();
    
                // The full path of the local file. 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();
                    // The image moderation service. The value is the service code that you configured for the rule in the AI Guardrails console. Example: baselineCheck.
                    // For more information about the supported services, see https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
                  	imageModerationRequest.Service = "baselineCheck";
                    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 operation to obtain the moderation result.
                    Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                        imageModerationRequest,
                        runtimeOptions
                    );
                    return response;
                }
                catch (Exception _err)
                {
                    Console.WriteLine(_err);
                    return null;
                }
            }
        }
    }
    # 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.client import Client as UtilClient
    from alibabacloud_tea_util import models as util_models
    import json
    import uuid
    
    
    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 based on your actual requirements.
            endpoint=endpoint
        )
        return Client(config)
    
    
    def invoke_function(access_key_id, access_key_secret, endpoint):
        # Note: To improve detection performance, reuse the instantiated client instead of creating a new one for each request. This helps avoid repeated connection establishment.
        client = create_client(access_key_id, access_key_secret, endpoint)
        # Create a RuntimeObject instance and configure runtime parameters.
        runtime = util_models.RuntimeOptions()
    
        # Construct the detection parameters.
        service_parameters = {
            # The URL of an image that is accessible over the public network.
            'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
            # The unique identifier of the data.
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            # The image detection service. This parameter specifies the serviceCode of the enhanced image moderation rule that you configured in the AI Guardrails console. Example: baselineCheck.
          	# For more information about the supported services, see https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            service='baselineCheck',
            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__':
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M.
        # We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
        # Common methods for obtaining environment variables:
        # Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        # Obtain the AccessKey secret of the 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 based on your actual requirements.
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-shanghai.aliyuncs.com')
        # Automatic routing.
        if response is not None:
            if UtilClient.equal_number(500,
                                       response.status_code) or (response.body is not None and 200 != response.body.code):
                # Switch the region to cn-beijing.
                response = invoke_function(access_key_id, access_key_secret, 'green-cip.cn-beijing.aliyuncs.com')
    
            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))
    

    Submit an asynchronous image detection task

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.ImageAsyncModerationRequest;
    import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
    import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody;
    import com.aliyun.teaopenapi.models.Config;
    import com.aliyun.teautil.models.RuntimeOptions;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    public class ImageAsyncModerationDemo {
    
    
        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 ImageAsyncModerationResponse 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("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            ImageAsyncModerationRequest imageAsyncModerationRequest = new ImageAsyncModerationRequest();
            imageAsyncModerationRequest.setService("baselineCheck");
            imageAsyncModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
            ImageAsyncModerationResponse response = null;
            try {
                response = client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        public static void main(String[] args) throws Exception {
            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";
            ImageAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageAsyncModerationResponseBody 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) {
                        ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        System.out.println("requestId = [" + data.getReqId() + "]");
                    } else {
                        System.out.println("image asyncmoderation not success. code:" + body.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
    
        }
    
    }
    

    Obtain asynchronous detection results

  32. Multi-service synchronous API integration example

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.ImageBatchModerationRequest;
    import com.aliyun.green20220302.models.ImageBatchModerationResponse;
    import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
    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 Demo {
    
    
        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 ImageBatchModerationResponse 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<>();
            // The region where the bucket of the file to be detected is located. Example: cn-shanghai
            serviceParameters.put("ossRegionId", "cn-shanghai");
            // The name of the bucket where the file to be detected is located. Example: bucket001
            serviceParameters.put("ossBucketName", "bucket001");
            // The file to be detected. Example: image/001.jpg
            serviceParameters.put("ossObjectName", "image/001.jpg");
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            ImageBatchModerationRequest imageBatchModerationRequest = new ImageBatchModerationRequest();
            imageBatchModerationRequest.setService("baselineCheck,baselineCheck_pro");
            imageBatchModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
            ImageBatchModerationResponse response = null;
            try {
                response = client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        public static void main(String[] args) throws Exception {
            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";
            ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageBatchModerationResponseBody 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) {
                        ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        List<ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult 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());
                }
            }
    
        }
    
    }
    
  33. Asynchronous API integration example

    Submit an asynchronous image detection task

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.ImageAsyncModerationRequest;
    import com.aliyun.green20220302.models.ImageAsyncModerationResponse;
    import com.aliyun.green20220302.models.ImageAsyncModerationResponseBody;
    import com.aliyun.teaopenapi.models.Config;
    import com.aliyun.teautil.models.RuntimeOptions;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    public class ImageAsyncModerationDemo {
    
    
        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 ImageAsyncModerationResponse 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());
            // The region where the bucket of the file to be detected is located. Example: cn-shanghai
            serviceParameters.put("ossRegionId", "cn-shanghai");
            // The name of the bucket where the file to be detected is located. Example: bucket001
            serviceParameters.put("ossBucketName", "bucket001");
            // The file to be detected. Example: image/001.jpg
            serviceParameters.put("ossObjectName", "image/001.jpg");
            ImageAsyncModerationRequest imageAsyncModerationRequest = new ImageAsyncModerationRequest();
            imageAsyncModerationRequest.setService("baselineCheck");
            imageAsyncModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
            ImageAsyncModerationResponse response = null;
            try {
                response = client.imageAsyncModerationWithOptions(imageAsyncModerationRequest, runtime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        public static void main(String[] args) throws Exception {
            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";
            ImageAsyncModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageAsyncModerationResponseBody 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) {
                        ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        System.out.println("requestId = [" + data.getReqId() + "]");
                    } else {
                        System.out.println("image asyncmoderation not success. code:" + body.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
    
        }
    
    }
    

    Obtain asynchronous image detection results

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.*;
    import com.aliyun.teaopenapi.models.Config;
    
    public class DescribeImageModerationResult {
        public static void main(String[] args) throws Exception {
            Config config = new Config();
            /**
             * 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.
             * Common ways to get environment variables:
             * Method 1:
             *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            config.setAccessKeyId("We recommend that you obtain the AccessKey ID from an environment variable");
            config.setAccessKeySecret("We recommend that you obtain the AccessKey secret from an environment variable");
            // Modify the region and endpoint as needed.
            config.setRegionId("cn-shanghai");
            config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
            // Connection timeout in milliseconds (ms).
            config.setReadTimeout(6000);
            // Read timeout in milliseconds (ms).
            config.setConnectTimeout(3000);
    
            Client client = new Client(config);
            DescribeImageModerationResultRequest describeImageModerationResultRequest = new DescribeImageModerationResultRequest();
            // The reqId returned when the task was submitted.
            describeImageModerationResultRequest.setReqId("1BB12784-FDDE-515D-AFE4-C5054F9F9269");
    
            try {
                DescribeImageModerationResultResponse response = client.describeImageModerationResult(describeImageModerationResultRequest);
                if (response.getStatusCode() == 200) {
                    DescribeImageModerationResultResponseBody result = response.getBody();
                    System.out.println("requestId=" + result.getRequestId());
                    System.out.println("code=" + result.getCode());
                    System.out.println("msg=" + result.getMsg());
                    if (200 == result.getCode()) {
                        DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                        System.out.println("data = " + JSON.toJSONString(data));
                    } else {
                        System.out.println("image async moderation result not success. code:" + result.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
  34. Multi-service synchronous API integration 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.ImageBatchModerationRequest;
    import com.aliyun.green20220302.models.ImageBatchModerationResponse;
    import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
    import com.aliyun.green20220302.models.ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData;
    import com.aliyun.green20220302.models.ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult;
    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 ImageBatchModerationUploads {
    
        // Specifies whether the service is deployed in a VPC.
        public static boolean isVPC = false;
    
        // File upload token: endpoint->token
        public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
    
        // Client for file upload requests. 
        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 for file upload requests.
         *
         * @param tokenData
         * @param isVPC
         */
        public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
            // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
            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 a 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 ImageBatchModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            // The full path of the local file, for example, D:\localPath\exampleFile.png.
            String filePath = "/Users/test/image/0544.jpg";
            // Get the file upload token.
            if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                tokenMap.put(endpoint,tokenResponse.getBody().getData());
            }
            // Client for file upload requests.
            getOssClient(tokenMap.get(endpoint), isVPC);
    
            // Upload the file.
            String objectName = uploadFile(filePath, tokenMap.get(endpoint));
    
            // Construct detection parameters.
            Map<String, String> serviceParameters = new HashMap<>();
            // File upload information.
            serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
            serviceParameters.put("ossObjectName", objectName);
            serviceParameters.put("dataId", UUID.randomUUID().toString());
    
            ImageBatchModerationRequest request = new ImageBatchModerationRequest();
            // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
            request.setService("baselineCheck,baselineCheck_pro");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
    
            ImageBatchModerationResponse response = null;
            try {
                response = client.imageBatchModerationWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        public static void main(String[] args) throws Exception {
            /**
             * 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.
             * Common ways to get environment variables:
             * Method 1:
             *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get 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.
            ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
            try {
                // Automatic routing.
                if (response != null) {
                    // Switch the region to cn-beijing.
                    if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                        // Modify the region and endpoint as needed.
                        response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                    }
                }
                // Print the detection results.
                if (response != null) {
                    if (response.getStatusCode() == 200) {
                        ImageBatchModerationResponseBody 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) {
                            ImageBatchModerationResponseBodyData data = body.getData();
                            System.out.println("data=" + JSON.toJSONString(data));
                        } else {
                            System.out.println("image batch moderation not success. code:" + body.getCode());
                        }
                    } else {
                        System.out.println("response not success. status:" + response.getStatusCode());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  35. Asynchronous API integration example

    Submit an asynchronous image detection task

    Obtain asynchronous image detection results

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.*;
    import com.aliyun.teaopenapi.models.Config;
    
    public class DescribeImageModerationResult {
        public static void main(String[] args) throws Exception {
            Config config = new Config();
            /**
             * 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.
             * Common ways to get environment variables:
             * Method 1:
             *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            config.setAccessKeyId("We recommend that you obtain the AccessKey ID from an environment variable");
            config.setAccessKeySecret("We recommend that you obtain the AccessKey secret from an environment variable");
            // Modify the region and endpoint as needed.
            config.setRegionId("cn-shanghai");
            config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
            // Connection timeout in milliseconds (ms).
            config.setReadTimeout(6000);
            // Read timeout in milliseconds (ms).
            config.setConnectTimeout(3000);
    
            Client client = new Client(config);
            DescribeImageModerationResultRequest describeImageModerationResultRequest = new DescribeImageModerationResultRequest();
            // The reqId returned when the task was submitted.
            describeImageModerationResultRequest.setReqId("1BB12784-FDDE-515D-AFE4-C5054F9F9269");
    
            try {
                DescribeImageModerationResultResponse response = client.describeImageModerationResult(describeImageModerationResultRequest);
                if (response.getStatusCode() == 200) {
                    DescribeImageModerationResultResponseBody result = response.getBody();
                    System.out.println("requestId=" + result.getRequestId());
                    System.out.println("code=" + result.getCode());
                    System.out.println("msg=" + result.getMsg());
                    if (200 == result.getCode()) {
                        DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                        System.out.println("data = " + JSON.toJSONString(data));
                    } else {
                        System.out.println("image async moderation result not success. code:" + result.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
  36. Multi-service synchronous API integration example

    import com.alibaba.fastjson.JSON;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.ImageBatchModerationRequest;
    import com.aliyun.green20220302.models.ImageBatchModerationResponse;
    import com.aliyun.green20220302.models.ImageBatchModerationResponseBody;
    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 Demo {
    
    
        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 ImageBatchModerationResponse 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("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            ImageBatchModerationRequest imageBatchModerationRequest = new ImageBatchModerationRequest();
            imageBatchModerationRequest.setService("baselineCheck,baselineCheck_pro");
            imageBatchModerationRequest.setServiceParameters(JSON.toJSONString(serviceParameters));
            ImageBatchModerationResponse response = null;
            try {
                response = client.imageBatchModerationWithOptions(imageBatchModerationRequest, runtime);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    
        public static void main(String[] args) throws Exception {
            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";
            ImageBatchModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageBatchModerationResponseBody 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) {
                        ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        List<ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageBatchModerationResponseBody.ImageBatchModerationResponseBodyDataResult 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());
                }
            }
    
        }
    
    }
    

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>3.3.3</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:

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>3.3.3</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==3.2.4
  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==3.2.4
    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==3.2.4
  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 3.2.4
  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;
    
    function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
            // Optional: set HTTP/HTTPS proxy if needed
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
    {
        // Reuse the client across requests.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        $runtime = new RuntimeOptions([]);
        $request = new ImageModerationRequest();
        $serviceParameters = array(
            'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',  // public URL
            'dataId' => uniqid()
        );
        // Set the service code configured in the AI Guardrails console.
        $request->service = "baselineCheck_global";
        $request->serviceParameters = json_encode($serviceParameters);
        return $client->imageModerationWithOptions($request, $runtime);
    }
    
    // Read credentials from environment variables — do not hardcode them.
    $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // Change the endpoint to match your region.
    $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());
    }
  3. Asynchronous API integration example

    Submit an asynchronous image detection task

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\ImageAsyncModerationRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return ImageAsyncModerationResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageAsyncModerationResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
        $request = new ImageAsyncModerationRequest();
        $serviceParameters = array(
            // The image to be detected, which is a publicly accessible URL.
            'imageUrl' => 'https://www.aliyun.com/img/000645/a6c2fa1b2c6de60e6c3a570995fd76e0.jpg',
            );
        // Image moderation service: The serviceCode configured in the AI Guardrails console for the Image Moderation Pro rule. Example: baselineCheck
        $request->service = "baselineCheck";
        $request->serviceParameters = json_encode($serviceParameters);
        // Submit for detection.
        return $client->imageAsyncModerationWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.aliyuncs.com";
    
    try {
        $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
        // Automatic routing.
        if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
            // Switch the region to cn-beijing.
            $endpoint = "green-cip.cn-beijing.aliyuncs.com";
            $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());
    }

    Obtain asynchronous image detection results

    <?php
    require('vendor/autoload.php');
    
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultResponse;
    use Darabonba\OpenApi\Models\Config;
    use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
    use AlibabaCloud\SDK\Green\V20220302\Green;
    use AlibabaCloud\SDK\Green\V20220302\Models\DescribeImageModerationResultRequest;
    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 the HTTP proxy.
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // Set the HTTPS proxy.
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    /**
     * Submit a detection task.
     * @param $accessKeyId
     * @param $accessKeySecret
     * @param $endpoint
     * @return DescribeImageModerationResultResponse
     */
    function invoke($accessKeyId, $accessKeySecret, $endpoint): DescribeImageModerationResultResponse
    {
        // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        // Create a RuntimeObject instance and set runtime parameters.
        $runtime = new RuntimeOptions([]);
        
        // Construct detection parameters.
        $request = new DescribeImageModerationResultRequest();
    
        $request->reqId = "2515AE5C-8EB3-5925-84C4-30F2195EAAD1";
        // Submit for detection.
        return $client->describeImageModerationResultWithOptions($request, $runtime);
    }
    
    /**
    * 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: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    * Get the AccessKey secret of the RAM user: getenv("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 = "green-cip.cn-shanghai.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());
    }

Detect local images

  1. Install both SDKs:

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

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 3.2.4
  3. 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;
    
    function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
    {
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        $runtime = new RuntimeOptions([]);
        $request = new ImageModerationRequest();
        $serviceParameters = array(
            'ossObjectName' => 'image/001.jpg',      // object path in the bucket
            'ossRegionId' => 'ap-southeast-1',        // region where the bucket is located
            'ossBucketName' => 'bucket001',           // your OSS bucket name
            'dataId' => uniqid()
        );
        $request->service = "baselineCheck_global";
        $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());
    }

Go SDK

Source code: Go SDK on GitHub

Detect publicly accessible images

  1. Install the SDK:

    go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
  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/google/uuid"
        "net/http"
        "os"
    )
    
    // Reuse the client across requests.
    func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
        config := &openapi.Config{
            AccessKeyId:     accessKeyId,
            AccessKeySecret: accessKeySecret,
            // Optional: set HTTP/HTTPS proxy if needed
            // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
            // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
            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{}{
                "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png", // public URL
                "dataId":   uuid.New(),
            },
        )
        imageModerationRequest := &green20220302.ImageModerationRequest{
            // Set the service code configured in the AI Guardrails console.
            Service:           tea.String("baselineCheck_global"),
            ServiceParameters: tea.String(string(serviceParameters)),
        }
    
        return client.ImageModerationWithOptions(imageModerationRequest, runtime)
    }
    
    func main() {
        // Read credentials from environment variables — do not hardcode them.
        accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
        accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
        // Change the endpoint to match your region.
        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)
            }
        }
    }
  3. Asynchronous API integration example

    Submit an asynchronous image detection task

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	green "github.com/alibabacloud-go/green-20220302/v3/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"),
    		AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"),
    		// The endpoint to access.
    		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
    		/**
    		 * Set a timeout period. The server-side full-link processing timeout is 10 seconds. Set the timeout accordingly.
    		 * If the ReadTimeout you set is less than the server processing time, a ReadTimeout exception will be thrown in the program.
    		 */
    		ConnectTimeout: tea.Int(3000),
    		ReadTimeout:    tea.Int(6000),
    	}
    	client, _err := green.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    
    	serviceParameters, _ := json.Marshal(
    		map[string]interface{}{
    			"imageUrl": "https://www.aliyun.com/d206c0754175bede745ce7618f73.jpg",
    		},
    	)
    	request := green.ImageAsyncModerationRequest{
    		Service:           tea.String("baselineCheck"),
    		ServiceParameters: tea.String(string(serviceParameters)),
    	}
    	result, err := client.ImageAsyncModeration(&request)
    	if err != nil {
    		fmt.Print(err.Error())
    	}
    	fmt.Printf("response is %#v\n", result.Body)
    }

    Obtain asynchronous image detection results

    package main
    
    import (
    	"fmt"
    	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
    	green "github.com/alibabacloud-go/green-20220302/v3/client"
    	"github.com/alibabacloud-go/tea/tea"
    )
    
    func main() {
    	config := &openapi.Config{
    		AccessKeyId: tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"),
    		AccessKeySecret: tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"),
    		// The endpoint to access.
    		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
    		/**
    		 * Set a timeout period. The server-side full-link processing timeout is 10 seconds. Set the timeout accordingly.
    		 * If the ReadTimeout you set is less than the server processing time, a ReadTimeout exception will be thrown in the program.
    		 */
    		ConnectTimeout: tea.Int(3000),
    		ReadTimeout:    tea.Int(6000),
    	}
    	client, _err := green.NewClient(config)
    	if _err != nil {
    		panic(_err)
    	}
    
    	request := green.DescribeImageModerationResultRequest{
    		ReqId:           tea.String("F30E5B52-12D7-59BB-95F0-5D3AA08ECABF"),
    	}
    	result, err := client.DescribeImageModerationResult(&request)
    	if err != nil {
    		fmt.Print(err.Error())
    	}
    	fmt.Printf("response is %#v\n", result.Body)
    }

Detect local images

  1. Install both SDKs:

    go get github.com/alibabacloud-go/green-20220302/v3
    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Call the API:

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 get github.com/alibabacloud-go/green-20220302/v3
  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@3.2.4
  2. Call the API:

    const RPCClient = require("@alicloud/pop-core");
    const { v4: uuidv4 } = require('uuid');
    
    async function main() {
        // Reuse the client across requests.
        var client = new RPCClient({
            // Read credentials from environment variables — do not hardcode them.
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
            // Change the endpoint to match your region.
            endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
            apiVersion: '2022-03-02',
            // Optional: set HTTP/HTTPS proxy if needed
            // httpProxy: "http://xx.xx.xx.xx:xxxx",
            // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
        });
    
        var params = {
            // Set the service code configured in the AI Guardrails console.
            "Service": "baselineCheck_global",
            "ServiceParameters": JSON.stringify({
                "dataId": uuidv4(),
                "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"  // public URL
            })
        };
    
        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));
    });

Detect local images

  1. Install both dependencies:

    npm install @alicloud/green20220302@3.2.4
    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");
    
    // Set to true when running in a VPC environment.
    var isVPC = false;
    // Cache upload tokens by endpoint.
    var tokenDic = new Array();
    var ossClient;
    
    function createClient(accessKeyId, accessKeySecret, endpoint) {
        return new RPCClient({
            accessKeyId: accessKeyId,
            accessKeySecret: accessKeySecret,
            endpoint: endpoint,
            apiVersion: '2022-03-02',
        });
    }
    
    function getOssClient(tokenData, isVPC) {
        ossClient = new OSS({
            accessKeyId: tokenData['AccessKeyId'],
            accessKeySecret: tokenData['AccessKeySecret'],
            stsToken: tokenData['SecurityToken'],
            endpoint: isVPC ? tokenData['OssInternalEndPoint'] : tokenData['OssInternetEndPoint'],
            bucket: tokenData['BucketName'],
        });
    }
    
    async function invoke(accessKeyId, accessKeySecret, endpoint) {
        var client = createClient(accessKeyId, accessKeySecret, endpoint);
        var requestOption = { method: 'POST', formatParams: false };
    
        // 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.
        if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
            var tokenResponse = await client.request('DescribeUploadToken', '', requestOption);
            tokenDic[endpoint] = tokenResponse.Data;
        }
    
        getOssClient(tokenDic[endpoint], isVPC);
        var split = filePath.split(".");
        var objectName = split.length > 1
            ? tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1]
            : tokenDic[endpoint].FileNamePrefix + uuidv4();
        await ossClient.put(objectName, path.normalize(filePath));
    
        var params = {
            "Service": "baselineCheck_global",
            "ServiceParameters": JSON.stringify({
                "ossBucketName": tokenDic[endpoint].BucketName,
                "ossObjectName": objectName
            })
        };
        return await client.request('ImageModeration', params, requestOption);
    }
    
    function main() {
        const accessKeyId = process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'];
        const accessKeySecret = process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'];
        var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com";
    
        invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
            console.log(JSON.stringify(response));
        }).catch(function (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@3.2.4
  3. Call the API:

    const RPCClient = require("@alicloud/pop-core");
    const { v4: uuidv4 } = require('uuid');
    
    async function main() {
        // Note: We recommend that you reuse the client instance to avoid repeatedly establishing connections and improve moderation performance.
        var client = new RPCClient({
    				/**
             * An Alibaba Cloud account AccessKey has permissions to call 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 and all resources in your account may be exposed to potential security risks.
             * The following content describes how 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: 'We recommend that you obtain the AccessKey ID of a RAM user from an environment variable.',
            accessKeySecret: 'We recommend that you obtain the AccessKey secret of a RAM user from an environment variable.',
            // Modify the region and endpoint as needed.
            endpoint: "https://green-cip.cn-shanghai.aliyuncs.com",
            apiVersion: '2022-03-02',
            // Configure an HTTP proxy.
            // httpProxy: "http://xx.xx.xx.xx:xxxx",
            // Configure an HTTPS proxy.
            // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
        });
    
        // Use the following code to create an API request and configure parameters:
        var params = {
            // The image moderation service. This parameter specifies the serviceCode that you configured for the image moderation rule in the AI Guardrails console. Example: baselineCheck
            // For more information about the supported services, see https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
            "Service": "baselineCheck",
            // The information about the OSS object to be moderated.
            "ServiceParameters": JSON.stringify({
                // The region where the bucket that stores the object to be moderated is located. Example: cn-shanghai
                "ossRegionId": "cn-shanghai",
                // The name of the bucket that stores the object to be moderated. Example: bucket001
                "ossBucketName": "bucket001",
                // The object to be moderated. Example: image/001.jpg
                "ossObjectName": "image/001.jpg",
                // The unique data ID.
                "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)
            //Automatic routing.
            if (response.Code === 500) {
                //Switch the region to cn-beijing.
                client.endpoint = "https://green-cip.cn-beijing.aliyuncs.com"
                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 3.2.4
  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 3.2.4

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 3.2.4
  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);
            }
        }
    }

If you have any questions, you can join the DingTalk group (Group No.: 35573806) and contact a product technical expert for help.

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:

Parameter

Type

Required

Description

Format

String

Yes

Response format: JSON (default) or XML

Version

String

Yes

API version in YYYY-MM-DD format. Value: 2022-03-02

AccessKeyId

String

Yes

Your AccessKey ID

Signature

String

Yes

HMAC-SHA1 signature string

SignatureMethod

String

Yes

Signature algorithm: HMAC-SHA1

Timestamp

String

Yes

Request time in ISO 8601 UTC format: yyyy-MM-ddTHH:mm:ssZ

SignatureVersion

String

Yes

Signature algorithm version: 1.0

SignatureNonce

String

Yes

Unique random number to prevent replay attacks; use a different value for each request

Action

String

Yes

API 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