Call APIs using an SDK

Updated at:

This topic describes how to use the Fraud Detection SDK, which provides a simple and convenient method to call API operations.

Introduction to SDK invocation methods

When you use the Fraud Detection SDK, you do not need to focus on complex processing such as signature verification and body format construction. We recommend that you use the Fraud Detection SDK. Currently, it supports Java, Python, PHP, C#, Go, Node.js, and Ruby (7 SDKs in total).

SDK for Java

For information about how to prepare the environment and install the Java SDK, see Alibaba Cloud SDK Developer Guide.

Java Maven dependency:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-saf</artifactId>
    <version>3.0.1</version>
</dependency>

Recommended Java Maven dependency manager:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <optional>true</optional>
    <version>4.5.25</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.68.noneautotype</version>
</dependency>
<dependency>        
    <groupId>org.apache.httpcomponents</groupId>        
    <artifactId>httpclient</artifactId>        
    <version>4.5.3</version>    
</dependency>    
<dependency>       
    <groupId>io.opentracing</groupId>       
    <artifactId>opentracing-util</artifactId>        
    <version>0.31.0</version>    
</dependency>

Click Link 1 or Link 2 to access the Java Maven repository.

Source code:

// An AccessKey pair for an Alibaba Cloud account has full permissions for all API operations. We recommend using a RAM user to call API operations or perform daily O&M.
// Do not hard-code your AccessKey ID and AccessKey Secret in your code. Leaking your AccessKey pair can compromise the security of all your resources.
// This example shows how to use the AccessKey pair of a RAM user from environment variables to authenticate API access. Before you run this sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
// Create and initialize a DefaultAcsClient instance. You need to initialize the instance only once.
DefaultProfile profile = DefaultProfile.getProfile(
    "<YOUR-REGION-ID>",          // The region ID. We recommend that you use cn-shanghai. 
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),// The AccessKey ID of the RAM user.
    System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // The AccessKey Secret of the RAM user.
// Configure the HTTP connection pool.
HttpClientConfig clientConfig = HttpClientConfig.getDefault();
clientConfig.setMaxRequestsPerHost(6);
clientConfig.setMaxIdleConnections(20);
// Configure the HTTP timeout.
clientConfig.setReadTimeoutMillis(10000);
clientConfig.setConnectionTimeoutMillis(3000);
profile.setHttpClientConfig(clientConfig);
IAcsClient client = new DefaultAcsClient(profile);


// Initiate the request.
ExecuteRequestRequest executeRequestRequest = new ExecuteRequestRequest();
//If you need to specify a different API version, you can modify it here. The default version is 2019-05-21.
//executeRequestRequest.setVersion(version);
// Specify the request method.
executeRequestRequest.setSysMethod(MethodType.POST);
// Specify the protocol. Only HTTPS is supported.
executeRequestRequest.setSysProtocol(ProtocolType.HTTPS);
// The service code for the product, such as account_abuse or coupon_abuse. For more information, see the service parameter in the "Common parameters" topic.
String service = "The service code for your product";
executeRequestRequest.setService(service);

// The service-specific parameters. For more information, see the documentation for the corresponding service. Optional parameters can be omitted.
Map<String, Object> serviceParams = new HashMap<String, Object>();

// A phone number, such as 13********3.
serviceParams.put("mobile", "13********3");
executeRequestRequest.setServiceParameters(JSONObject.toJSONString(serviceParams));
executeRequestRequest.setAcceptFormat(FormatType.JSON);
try {
    ExecuteRequestResponse httpResponse = client.getAcsResponse(executeRequestRequest);
    System.out.println("httpResponse:" + JSONObject.toJSONString(httpResponse));
} catch (Exception e) {
    e.printStackTrace();
}

SDK for Python

Click here to download the source code of Fraud Detection SDK for Python.

For information about how to prepare the environment and install the Python SDK, see Alibaba Cloud SDK Developer Guide.

  1. Install the SDK core library.

    • If you are using Python 2.x, run the following command to install the Alibaba Cloud SDK core library:

      pip install aliyun-python-sdk-core
    • If you are using Python 3.x, run the following command to install the Alibaba Cloud SDK core library:

      pip install aliyun-python-sdk-core-v3
  2. Install the cloud product SAF SDK.

    pip install aliyun-python-sdk-saf

Python use case:

import os
from aliyunsdkcore import client
from aliyunsdksaf.request.v20190521 import ExecuteRequestRequest
# An Alibaba Cloud account AccessKey has access permissions to all API operations. We recommend that you use a RAM user for API access or O&M.
# We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
# This example uses the AccessKey pair of a RAM user from environment variables to authenticate API access. Before you run this sample code, make sure that you have configured the following environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
clt = client.AcsClient(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],'cn-shanghai')
# Set parameters
request = ExecuteRequestRequest.ExecuteRequestRequest()
request.set_accept_format('json')
# For the Service product, see the Service field description in the [Common Parameters] document
request.add_query_param('Service', 'purchased product Service')
request.add_query_param('ServiceParameters', 'input JSON string')
# Send the request
response = clt.do_action_with_exception(request)
print(response)
                                

Use scenario-specific risk control:

# -*- coding: utf-8 -*-
import os
import sys

from typing import List

from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> OpenApiClient:
        """
        Use your AccessKey ID and AccessKey secret to initialize a client.
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # Required. Specify your AccessKey ID.
            access_key_id=access_key_id,
            # Required. Specify your AccessKey Secret.
            access_key_secret=access_key_secret
        )
        # Specify an endpoint. For more information, visit https://api.aliyun.com/product/saf.
        config.endpoint = f'saf.ap-southeast-1.aliyuncs.com'
        return OpenApiClient(config)

    @staticmethod
    def create_api_info() -> open_api_models.Params:
        """
        Configure API-related parameters.
        @param path: params
        @return: OpenApi.Params
        """
        params = open_api_models.Params(
            # The name of the operation.
            action='ExecuteRequestSG',
            # The version number of the operation.
            version='2019-05-21',
            # The protocol of the operation.
            protocol='HTTPS',
            # The HTTP method of the operation.
            method='POST',
            auth_type='AK',
            style='RPC',
            # The path to the operation.
            pathname=f'/',
            # The format of the request body.
            req_body_type='json',
            # The format of the response body.
            body_type='json'
        )
        return params

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is for reference only. We recommend that you use STS, which provides higher security.
        client = Sample.create_client(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
        params = Sample.create_api_info()
        # query params
        queries = {}
        queries['ServiceParameters'] = '{"email":"example@alibabacloud.com","ip":"x.x.x.x","deviceToken":"******"}'
        queries['Service'] = 'account_abuse_intl_pro'
        # runtime options
        runtime = util_models.RuntimeOptions()
        request = open_api_models.OpenApiRequest(
            query=OpenApiUtilClient.query(queries)
        )
        # Write your code to print the response of the API operation based on your business requirements.
        # The return value is of the Map type. You can obtain the following types of data from the Map: response body, response header, and HTTP status code statusCode.
        client.call_api(params, request, runtime)

if __name__ == '__main__':
    Sample.main(sys.argv[1:])

SDK for PHP

Click here to download the source code of Fraud Detection SDK for PHP.

For information about how to prepare the environment and install the PHP SDK, see Alibaba Cloud SDK Developer Guide.

PHP use case:

<?php
include_once 'aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config.php';
use saf\Request\V20190521 as saf;
// Initialize
// An Alibaba Cloud account AccessKey has access permissions to all API operations. We recommend that you use a RAM user for API access or O&M.
// We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
// This example uses the AccessKey pair of a RAM user from environment variables to authenticate API access. Before you run this sample code, make sure that you have configured the following environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
$iClientProfile = DefaultProfile::getProfile("cn-shanghai", getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'));
$client = new DefaultAcsClient($iClientProfile);
// Set parameters
$request = new saf\ExecuteRequestRequest();
// For the Service product, see the Service field description in the [Common Parameters] document
$request->setService('purchased product Service');
$request->setServiceParameters('input JSON string');
// Send the request
$response = $client->getAcsResponse($request);
print_r("<br>");
print_r("test");
print_r("\r\n");
print_r($response);
print_r($client);
?>

Use the decision engine:

<?php
namespace AlibabaCloud\SDK\Sample;

use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;

class Sample {

    /**
     * Use your AccessKey ID and AccessKey secret to initialize a client.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return OpenApiClient Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // Required. Specify your AccessKey ID.
            "accessKeyId" => $accessKeyId,
            // Required. Specify your AccessKey Secret.
            "accessKeySecret" => $accessKeySecret
        ]);
        // Specify an endpoint. For more information, visit https://api.aliyun.com/product/saf.
        $config->endpoint = "saf.ap-southeast-1.aliyuncs.com";
        return new OpenApiClient($config);
    }

    /**
     * Configure API-related parameters.
     * @return Params OpenApi.Params
     */
    public static function createApiInfo(){
        $params = new Params([
            // The name of the operation.
            "action" => "RequestDecision",
            // The version number of the operation.
            "version" => "2019-05-21",
            // The protocol of the operation.
            "protocol" => "HTTPS",
            // The HTTP method of the operation.
            "method" => "POST",
            "authType" => "AK",
            "style" => "RPC",
            // The path to the operation.
            "pathname" => "/",
            // The format of the request body.
            "reqBodyType" => "json",
            // The format of the response body.
            "bodyType" => "json"
        ]);
        return $params;
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is for reference only. We recommend that you use STS, which provides higher security.
        $client = self::createClient(getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'));
        $params = self::createApiInfo();
        // query params
        $queries = [];
        $queries["ServiceParameters"] = "{\"email\":\"example@alibabacloud.com\",\"ip\":\"x.x.x.x\",\"deviceToken\":\"******\"}";
        $queries["EventCode"] = "de_*****";
        // runtime options
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "query" => OpenApiUtilClient::query($queries)
        ]);
        // Write your code to print the response of the API operation based on your business requirements.
        // The return value is of the Map type. It contains the following types of data: response body, response header, and HTTP status code.
        $client->callApi($params, $request, $runtime);
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));

Use scenario-specific risk control:

<?php
namespace AlibabaCloud\SDK\Sample;

use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;

class Sample {

    /**
     * Use your AccessKey ID and AccessKey secret to initialize a client.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return OpenApiClient Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // Required. Specify your AccessKey ID.
            "accessKeyId" => $accessKeyId,
            // Required. Specify your AccessKey Secret.
            "accessKeySecret" => $accessKeySecret
        ]);
        // Specify an endpoint. For more information, visit https://api.aliyun.com/product/saf.
        $config->endpoint = "saf.ap-southeast-1.aliyuncs.com";
        return new OpenApiClient($config);
    }

    /**
     * Configure API-related parameters.
     * @return Params OpenApi.Params
     */
    public static function createApiInfo(){
        $params = new Params([
            // The name of the operation.
            "action" => "ExecuteRequestSG",
            // The version number of the operation.
            "version" => "2019-05-21",
            // The protocol of the operation.
            "protocol" => "HTTPS",
            // The HTTP method of the operation.
            "method" => "POST",
            "authType" => "AK",
            "style" => "RPC",
            // The path to the operation.
            "pathname" => "/",
            // The format of the request body.
            "reqBodyType" => "json",
            // The format of the response body.
            "bodyType" => "json"
        ]);
        return $params;
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured.
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code is for reference only. We recommend that you use STS, which provides higher security.
        $client = self::createClient(getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'));
        $params = self::createApiInfo();
        // query params
        $queries = [];
        $queries["ServiceParameters"] = "{\"email\":\"example@alibabacloud.com\",\"ip\":\"x.x.x.x\",\"deviceToken\":\"******\"}";
        $queries["Service"] = "account_abuse_intl_pro";
        // runtime options
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "query" => OpenApiUtilClient::query($queries)
        ]);
        // Write your code to print the response of the API operation based on your business requirements.
        // The return value is of the Map type. It contains the following types of data: response body, response header, and HTTP status code.
        $client->callApi($params, $request, $runtime);
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));

SDK for C#

Click here to download the source code of Fraud Detection SDK for C#.

For information about how to prepare the environment and install the C# SDK, see Alibaba Cloud SDK Developer Guide.

C# use case

using System;
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Auth;

namespace CommonRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
        AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
            Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            /* use STS Token
            AlibabaCloudCredentialsProvider provider = new StsCredentialProvider(
                Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), 
                Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), 
                Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN"));
            */
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", provider);
            DefaultAcsClient client = new DefaultAcsClient(profile, provider);

            CommonRequest request = new CommonRequest();

            request.Method = MethodType.POST;
            request.Domain = "saf.cn-hangzhou.aliyuncs.com";
            request.Version = "2019-05-21";
            request.Action = "ExecuteRequestSG";
            // request.Protocol = ProtocolType.HTTP;

            try {
                CommonResponse response = client.GetCommonResponse(request);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

SDK for Go

Click here to download the source code of Fraud Detection SDK for Go.

For information about how to prepare the environment and install the Go SDK, see Alibaba Cloud SDK Developer Guide.

Golang use cases:

package main
import (
    "os"
    "fmt"
    "github.com/aliyun/alibaba-cloud-sdk-go/services/saf"
)
func main() {
    // An Alibaba Cloud account AccessKey has access permissions to all API operations. We recommend that you use a RAM user for API access or O&M.
    // We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
    // This example uses the AccessKey pair of a RAM user from environment variables to authenticate API access. Before you run this sample code, make sure that you have configured the following environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
    client, err := saf.NewClientWithAccessKey("cn-shanghai", os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
    request := saf.CreateExecuteRequestRequest()
    endpoints.AddEndpointMapping("cn-shanghai", "saf", "saf.cn-shanghai.aliyuncs.com")
    // For the Service product, see the Service field description in the [Common Parameters] document
    request.Service = "purchased product Service"
    request.ServiceParameters = "input JSON string"
    request.Scheme = "https"
    response, err := client.ExecuteRequest(request)
    if err != nil {
        fmt.Print(err.Error())
    }
    fmt.Printf("response code is %#v\n", response.Code)
    fmt.Printf("response data is %#v\n", response.Data)
    fmt.Printf("response message is %#v\n", response.Message)
    fmt.Printf("response requestId is %#v\n", response.RequestId)
}

Node.js

Click here to download the source code of Fraud Detection SDK for Node.js.

For information about how to prepare the environment and install the Node.js SDK, see Alibaba Cloud SDK Developer Guide.

Run the following command to install the @alicloud/pop-core module. The --save parameter will write the module to the application's package.json file as a dependency module.

$ npm install @alicloud/pop-core --save

Test case of Node.js SDK:

const Core = require('@alicloud/pop-core');
// An Alibaba Cloud account AccessKey has access privileges to all APIs. We recommend that you use a RAM user for API access or routine O&M.
// We strongly recommend that you do not save the AccessKey ID and AccessKey Secret in your code. Otherwise, your AccessKey may be leaked and the security of all resources in your account may be threatened.
// This example authenticates API access by reading the RAM user AccessKey from environment variables. Before you run this sample code, make sure that you have configured these two environment variables: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.
var client = new Core({
  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  endpoint: 'https://saf.cn-shanghai.aliyuncs.com',
  apiVersion: '2019-05-21'
});
var params = {
  "RegionId": "cn-shanghai",
  // For the product Service, see the Service field description in the [Common Parameters] document
  "Service": "purchased product Service",
  "ServiceParameters": "input parameter JSON string"
}
var requestOption = {
  method: 'POST'
};
client.request('ExecuteRequest', params, requestOption).then((result) => {
  console.log(JSON.stringify(result));
}, (ex) => {
  console.log(ex);
})

SDK for Ruby

Click here to download the Ruby SDK source code.

For information about how to prepare the environment and install the Ruby SDK, see Alibaba Cloud SDK Developer Guide.

Run the following command to install Alibaba Cloud Core SDK for Ruby:

$ gem install aliyunsdkcore

Test case of Fraud Detection SDK for Ruby:

require 'aliyunsdkcore'

# An Alibaba Cloud account AccessKey has access privileges 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 store the AccessKey ID and AccessKey secret in your code. Otherwise, your AccessKey pair may be leaked, which threatens the security of all resources in your account.
# This example authenticates API access by reading the RAM user AccessKey from environment variables.
# Before you run this sample code, make sure that the following environment variables are configured: ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET.

client = RPCClient.new(
  access_key_id: ENV['ALIBABA_CLOUD_ACCESS_KEY_ID'],
  access_key_secret: ENV['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
  endpoint: 'https://saf.cn-shanghai.aliyuncs.com',
  api_version: '2019-05-21'
)
response = client.request(
  action: 'ExecuteRequest',
  params: {
    "RegionId": "cn-shanghai",
    # For information about the Service parameter, see the Service field description in the "Common Parameters" document.
    "Service": "purchased product Service",
    "ServiceParameters": "input parameter JSON string"
  },
  opts: {
    method: 'POST'
  }
)
print response

References