Integrate the Text Moderation 2.0 PLUS SDK into your application to detect harmful text content across multiple languages using a single API call.
Prerequisites
Before you begin, make sure you have:
An Alibaba Cloud account
A Resource Access Management (RAM) user with the
AliyunYundunGreenWebFullAccesspolicyAn AccessKey pair associated with that RAM user
The
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETenvironment variables set in your runtime environment
Step 1: Activate the service
Go to the Activate Service page and activate the Text Moderation 2.0 service.2.02.02.02.02.02.02.02.02.0
The default billing method is pay-as-you-go. You are charged based on daily usage. If you do not use the service, you are not charged.
Step 2: Set up a RAM user
The Content Moderation API requires a RAM user with the appropriate system policy. Using a RAM user instead of your root account limits the blast radius of a credential leak.
Log on to the RAM console as a RAM administrator.
Create a RAM user. For details, see Create a RAM user.
Grant the
AliyunYundunGreenWebFullAccesssystem policy to the RAM user. For details, see Grant permissions to a RAM user.Create an AccessKey pair for the RAM user. For details, see Obtain an AccessKey.
Do not store your AccessKey ID or AccessKey secret in code. Set them as environment variables (ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET) and read them at runtime. For credential configuration details, see Configure credentials.
Step 3: Install the SDK and make your first call
All examples use the comment_multilingual_pro_global service and the Singapore endpoint (green-cip.ap-southeast-1.aliyuncs.com). Change the region and endpoint to match your deployment.
Supported regions
| Region | Public endpoint | VPC endpoint |
|---|---|---|
| Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com |
| UK (London) | green-cip.eu-west-1.aliyuncs.com | Not available |
| US (Virginia) | green-cip.us-east-1.aliyuncs.com | green-cip-vpc.us-east-1.aliyuncs.com |
| US (Silicon Valley) | green-cip.us-west-1.aliyuncs.com | Not available |
| Germany (Frankfurt) | green-cip.eu-central-1.aliyuncs.com | Not available |
The comment_multilingual_pro_global service is available in Singapore. For the full list of services per region, see Text Moderation Enhanced 2.0 Multilingual PLUS Service.
For SDK samples in languages not listed here, use the OpenAPI Explorer to generate code for any supported language.
Java
Java 1.8 and later are supported. Source code: GitHub or OSS path.
1. Add the dependency to your `pom.xml`:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>2.2.11</version>
</dependency>2. Call the API:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationPlusRequest;
import com.aliyun.green20220302.models.TextModerationPlusResponse;
import com.aliyun.green20220302.models.TextModerationPlusResponseBody;
import com.aliyun.teaopenapi.models.Config;
public class TextModerationPlusDemo {
public static void main(String[] args) throws Exception {
Config config = new Config();
/**
* An AccessKey of an Alibaba Cloud account has permissions on all API operations. This is a security risk.
* We recommend that you use a RAM user to call API operations or perform routine O&M.
* To authenticate your request, you need to configure your credentials.
* We recommend that you use an environment variable to configure your credentials.
* For example, you can retrieve the AccessKey ID and AccessKey Secret of a RAM user from the following environment variables:
* System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// The region ID. Set it to the region where your service is deployed.
config.setRegionId("ap-southeast-1");
// The endpoint of the service.
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
// Specifies the read timeout in milliseconds (ms).
config.setReadTimeout(6000);
// Specifies the connect timeout in milliseconds (ms).
config.setConnectTimeout(3000);
// Set an HTTP proxy.
//config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
// Set an HTTPS proxy.
//config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
serviceParameters.put("content", "This is sample text for moderation.");
TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
// The type of the detection service.
textModerationPlusRequest.setService("text_multilingual_pro_global");
textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());
try {
TextModerationPlusResponse response = client.textModerationPlus(textModerationPlusRequest);
if (response.getStatusCode() == 200) {
TextModerationPlusResponseBody result = response.getBody();
System.out.println(JSON.toJSONString(result));
System.out.println("requestId = " + result.getRequestId());
System.out.println("code = " + result.getCode());
System.out.println("msg = " + result.getMessage());
Integer code = result.getCode();
if (200 == code) {
TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
System.out.println(JSON.toJSONString(data, true));
} else {
System.out.println("Text moderation failed. Code: " + code);
}
} else {
System.out.println("The request failed. Status code: " + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Expected output:
requestId = AAAAAA-BBBB-CCCCC-DDDD-EEEEEEEE****
code = 200
msg = OK
{
"Result": [
{"Label": "political_entity", "Description": "Suspected political entity", "Confidence": 100.0, "RiskWords": "Word A,Word B,Word C"}
],
"RiskLevel": "high"
}Python
Python 3.6 and later are supported. Source code: PyPI.
1. Install the package:
pip install alibabacloud_green20220302==2.2.112. Call the API:
# coding=utf-8
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
# 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'],
connect_timeout=10000, # Connection timeout in milliseconds
read_timeout=3000, # Read timeout in milliseconds
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
client = Client(config)
service_parameters = {'content': 'Test text content'}
request = models.TextModerationPlusRequest(
service='comment_multilingual_pro_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = client.text_moderation_plus(request)
if response.status_code == 200:
print('Success. result: {}'.format(response.body))
else:
print('Request failed. status: {}, result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Expected output:
Success. result: {"Code": 200, "Data": {"Result": [...], "RiskLevel": "high"}, "Message": "OK", "RequestId": "..."}# -*- coding: utf-8 -*-
# This example requires Python 3.6 or later.
import os
import json
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
# An AccessKey of an Alibaba Cloud account has permissions on all API operations. This is a security risk.
# We recommend that you use a RAM user to call API operations or perform routine O&M.
# Do not hard-code your AccessKey ID and AccessKey Secret in the code.
# We recommend that you load your credentials from environment variables.
# For example, you can retrieve the AccessKey ID and AccessKey Secret of a RAM user from the following environment variables:
# os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID')
# os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
config = Config(
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# Specifies the connect timeout in milliseconds (ms).
connect_timeout=10000,
# Specifies the read timeout in milliseconds (ms).
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
clt = Client(config)
serviceParameters = {
'content': 'This is sample text for moderation.'
}
textModerationPlusRequest = models.TextModerationPlusRequest(
# The type of the detection service.
service='text_multilingual_pro_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.text_moderation_plus(textModerationPlusRequest)
if response.status_code == 200:
# The API call is successful.
result = response.body
print(f"API call successful. Result: {result}")
else:
print(f"API call failed. Status code: {response.status_code}, Response: {response}")
except Exception as err:
print(err)PHP
PHP 5.6 and later are supported. Source code: Packagist.
1. Install the package:
composer require alibabacloud/green-20220302 2.2.102. Call the API:
<?php
require('vendor/autoload.php');
use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationPlusRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
$config = new Config([
/**
* An AccessKey of an Alibaba Cloud account has permissions on all API operations. This is a security risk.
* We recommend that you use a RAM user to call API operations or perform routine O&M.
* Do not hard-code your AccessKey ID and AccessKey Secret in the code.
* We recommend that you load your credentials from environment variables.
* For example, you can retrieve the AccessKey ID and AccessKey Secret of a RAM user from the following environment variables:
* getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Set an HTTP proxy.
// "httpProxy" => "http://10.10.xx.xx:xxxx",
// Set an HTTPS proxy.
// "httpsProxy" => "https://10.10.xx.xx:xxxx",
"endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
"regionId" => "ap-southeast-1"
]);
// Note: For better performance, reuse the client instance to avoid creating new connections for each request.
$client = new Green($config);
$request = new TextModerationPlusRequest();
$request->service = "text_multilingual_pro_global";
$serviceParameters = array("content" => "This is sample text for moderation.");
$request->serviceParameters = json_encode($serviceParameters);
$runtime = new RuntimeOptions();
$runtime->readTimeout = 6000;
$runtime->connectTimeout = 3000;
try {
$response = $client->textModerationPlusWithOptions($request, $runtime);
print_r($response->body);
if (200 != $response->statusCode) {
print_r("The request failed. Code: " . $response->statusCode);
return;
}
$body = $response->body;
print_r("requestId = " . $body->requestId . "\n");
print_r("code = " . $body->code . "\n");
print_r("message = " . $body->message . "\n");
if (200 != $body->code) {
print_r("Text moderation failed. Code: " . $body->code);
}
$data = $body->data;
print_r("data = " . json_encode($data));
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}Go
1. Clone the SDK:
git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v22. Call the API:
package main
import (
"encoding/json"
"fmt"
"os"
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"
"net/http"
)
func main() {
// Hard-coding your AccessKey in the code is not recommended. This may lead to security risks.
// For improved security, we recommend that you use STS credentials.
config := &openapi.Config{
/**
* An AccessKey of an Alibaba Cloud account has permissions on all API operations. This is a security risk.
* We recommend that you use a RAM user to call API operations or perform routine O&M.
* To authenticate your request, you need to configure your credentials.
* We recommend that you use an environment variable to configure your credentials.
* For example, you can retrieve the AccessKey ID and AccessKey Secret of a RAM user from the following environment variables:
* os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
// Set an HTTP proxy.
// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
// Set an HTTPS proxy.
// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
/**
* Set timeouts. The server-side processing timeout for this operation is 10 seconds.
* If you set a read timeout that is shorter than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a runtime options object.
runtime := &util.RuntimeOptions{}
runtime.ReadTimeout = tea.Int(10000)
runtime.ConnectTimeout = tea.Int(10000)
serviceParameters, _ := json.Marshal(
map[string]interface{}{
"content": "This is sample text for moderation.",
},
)
request := green20220302.TextModerationPlusRequest{
Service: tea.String("text_multilingual_pro_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
result, _err := client.TextModerationPlusWithOptions(&request, runtime)
if _err != nil {
panic(_err)
}
if *result.StatusCode != http.StatusOK {
fmt.Printf("The request failed. Status code: %d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("The request is successful. requestId: %s, code: %d, msg: %s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code != http.StatusOK {
fmt.Printf("Text moderation failed. Code: %d\n", *body.Code)
return
}
data := body.Data
fmt.Printf("Text moderation data: %s\n", *data)
}Node.js
Source code: npm.
1. Install the package:
npm install @alicloud/green20220302@2.2.102. Call the API:
const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: For better performance, reuse the client instance instead of creating a new one for each request.
// Hard-coding your AccessKey in the code can lead to security risks. The following code is for demonstration only.
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
endpoint: `green-cip.ap-southeast-1.aliyuncs.com`,
});
return new Green20220302.default(config);
}
static async main() {
const client = Client.createClient();
// Create a request object.
const textModerationPlusRequest = new Green20220302.TextModerationPlusRequest({
// The service for Text Moderation Enhanced PLUS. For more information, see https://www.alibabacloud.com/help/en/content-moderation/latest/api-green-2022-03-02-textmoderationplus
"service": "text_multilingual_pro_global",
"serviceParameters": JSON.stringify({
// The text to be moderated.
"content": "sample text"})
});
// Create a runtime options object.
const runtime = new Util.RuntimeOptions();
try {
// Send the request and retrieve the response.
const response = await client.textModerationPlusWithOptions(textModerationPlusRequest, runtime);
console.log(JSON.stringify(response.body));
} catch (error) {
// The following code is for demonstration only. In a production environment, you must handle exceptions properly.
// Error message.
console.log('Error occurred:', error.message);
}
}
}
Client.main();C\#
Source code: NuGet.
1. Add the package:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.102. Call the API:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace AlibabaCloud.SDK.Green20220302
{
public class TextModerationPlusDemo
{
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");
string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
// Reuse the client instance to avoid repeated connection setup
Client client = CreateClient(accessKeyId, accessKeySecret, endpoint);
var runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
var request = new Models.TextModerationPlusRequest();
request.Service = "comment_multilingual_pro_global";
var task = new Dictionary<string, object> { { "content", "Test text" } };
request.ServiceParameters = JsonConvert.SerializeObject(task);
try
{
var response = client.TextModerationPlusWithOptions(request, 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)
{
var config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
// Optional: set HTTP or HTTPS proxy
// HttpProxy = "http://10.10.xx.xx:xxxx",
// HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
Endpoint = endpoint,
};
return new Client(config);
}
}
}Native HTTPS calls
Use the native HTTPS approach only if you cannot use an SDK — for example, when building a mobile app where package size is critical, or when you have dependency constraints that prevent SDK adoption. In all other cases, use the SDK.
The native approach requires you to manually handle request signing, URL encoding, and header assembly.
Request details
URL:
https://green-cip.{region}.aliyuncs.comProtocol: HTTPS
Method: POST
API version:
2022-03-02Action:
TextModerationPlus
Common request parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
Format | String | Yes | Response format. Valid values: JSON (default), XML. |
Version | String | Yes | API version in YYYY-MM-DD format. Use 2022-03-02. |
AccessKeyId | String | Yes | Your AccessKey ID. |
Signature | String | Yes | The computed request signature. |
SignatureMethod | String | Yes | Signature algorithm. Use HMAC-SHA1. |
Timestamp | String | Yes | Request timestamp in ISO 8601 UTC format: yyyy-MM-ddTHH:mm:ssZ (e.g., 2022-12-12T01:13:14Z). |
SignatureVersion | String | Yes | Signature algorithm version. Use 1.0. |
SignatureNonce | String | Yes | Unique random string per request, used to prevent replay attacks. |
Action | String | Yes | API operation name. Use TextModerationPlus. |
Example request
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=TextModerationPlus
&AccessKeyId=123****cip
&Timestamp=2022-12-12T12:00:00Z
&Service=text_multilingual_pro_global
&ServiceParameters={"content": "sample text"}Signing requests
The service authenticates each request using HMAC-SHA1 symmetric encryption. Follow these steps to sign a request:
Build the canonicalized query string:
Collect all request parameters except
Signatureand sort them alphabetically.URL-encode parameter names and values in UTF-8. Apply these rules:
Characters
A–Z,a–z,0–9,-,_,., and~are not encoded.Other characters are encoded as
%XY, whereXYis the uppercase hex ASCII value (e.g.,"→%22).Extended UTF-8 characters are encoded as
%XY%ZA….Encode spaces as
%20, not+.If using a URL encoding library (e.g.,
java.net.URLEncoder), replace+with%20,*with%2A, and%7Ewith~in the output.
Join each encoded name-value pair with
=.Join all pairs with
&in alphabetical order.
Build the string to sign:
StringToSign = HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)Where
percentEncode("/")=%2F.Compute the HMAC-SHA1 signature: Use
AccessKey secret + "&"(ASCII 38) as the signing key and apply SHA1.Base64-encode the HMAC value to get the signature string.
URL-encode the signature per RFC3986 and append it as the
Signatureparameter.
Understanding the response
All SDK examples return a response with the following structure:
| Field | Type | Description |
|---|---|---|
Code | Integer | 200 indicates success. Any other value indicates a moderation or API error. |
Message | String | OK on success, or an error description. |
RequestId | String | Unique ID for the request, useful for troubleshooting. |
Data.Result | Array | List of detected risk labels. |
Data.RiskLevel | String | Overall risk level: high, medium, or low. |
Each item in Data.Result contains:
| Field | Type | Description |
|---|---|---|
Label | String | The risk category (e.g., political_entity, political_figure). |
Description | String | A human-readable description of the detected risk. |
Confidence | Float | Confidence level of the detection, from 0 to 100. |
RiskWords | String | Comma-separated list of flagged words or phrases. |
Example response:
{
"Code": 200,
"Data": {
"Result": [
{
"Label": "political_entity",
"Description": "Suspected political entity",
"Confidence": 100.0,
"RiskWords": "Word A,Word B,Word C"
},
{
"Label": "political_figure",
"Description": "Suspected political figure",
"Confidence": 100.0,
"RiskWords": "Word A,Word B,Word C"
}
],
"RiskLevel": "high"
},
"Message": "OK",
"RequestId": "AAAAAA-BBBB-CCCCC-DDDD-EEEEEEEE****"
}What's next
Text Moderation Enhanced 2.0 Multilingual PLUS Service — full API reference including all supported services and parameters
Text Moderation Enhanced 2.0 General Service SDK and Integration Guide — if you previously integrated the general service version
Configure credentials — recommended credential management approaches for production use