This topic provides examples of how to call Robotic Process Automation (RPA) server-side APIs in Python and Java.
Configure access credentials
To call an API, you must first configure environment variables to read access credentials. For more information about how to configure environment variables,
The environment variable name for the Robotic Process Automation AccessKey ID is RPA_AK_ENV, and the environment variable name for the AccessKey secret is RPA_SK_ENV.
Configuration on Linux and macOS
Run the following commands:
export RPA_AK_ENV =<access_key_id>
export RPA_SK_ENV=<access_key_secret>
Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey secret.
How to configure Windows system environment variables
Right-click This PC and select Properties.
In the window that appears, select Advanced system settings.
On the Advanced tab of the System Properties window, click Environment Variables.
In the System variables section, add the RPA_AK_ENV and RPA_SK_ENV environment variables. Set their values to the AccessKey information that you obtained from the System Settings page of the RPA console.
Restart your computer.
Call examples
Python example
import requests import base64 import datetime import hmac import random from hashlib import sha1 from urllib import parse import json import os def start(): # This example shows how to call the API to get client information. # AccessKey secret AccessSecret = os.getenv('RPA_SK_ENV') # Request method method = 'POST' # Common request parameters AccessKeyId = os.getenv('RPA_AK_ENV') signature_method = "HMAC-SHA1" signature_version = "1.0" signature_nonce = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 26)) timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") version = "20200430" data_format = "json" # API-specific request parameters appId = "your_app_id" clientId = "your_robot_id" appParams= json.dumps([{"name": "example_param_1", "value": "example_content_1"},{"name": "example_param_2", "value": "example_content_2"}]) params = {"AccessKeyId": AccessKeyId, "Format": data_format, "SignatureMethod": signature_method, "SignatureNonce": signature_nonce, "SignatureVersion": signature_version, "Timestamp": timestamp, "Version": version, "appId": appId, "clientId":clientId, "appParams":appParams, } # print(params) # Parameters for signature calculation: AccessKey secret, request method, common request parameters, and API-specific parameters. # Step 1: Sort the common and API-specific request parameters. items = list(params.keys()) items.sort() temp_list = [] for i in items: if i == 'AppParams' or i == 'appParams': temp_list.append(parse.quote(i) + "=" + parse.quote(params[i])) continue temp_list.append(parse.quote_plus(i) + "=" + parse.quote_plus(params[i])) temp_string = "&".join(temp_list) # Step 2: Construct the canonicalized query string. StringToSign = method.upper() + "&%2F&" + parse.quote_plus(temp_string) # print("===============" + StringToSign) # Step 3: Generate the signature parameter. h = hmac.new((AccessSecret + '&').encode("utf-8"), StringToSign.encode("utf-8"), sha1).digest() Signature = base64.b64encode(h) # Print the signature parameter. # print(Signature) # Print other parameters. The timestamp and SignatureNonce parameters are required when you send the request. # print(timestamp) # print(signature_nonce) # Create a service-based task. url = 'https://console-rpa.aliyun.com/rpa/openapi/task/createServiceTask' params['Signature'] = Signature req = requests.post(url=url, data=params) # req = requests.get(url=url,params=params) print(req.json()) if __name__ == '__main__': start()Java example
package com.company; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; public class Main { /** * Server address. This example uses an RPA public cloud cluster. */ public static final String SERVER = "https://console-rpa.aliyun.com"; /** * API path. This example uses createServiceTask. */ public static final String PATH = "/rpa/openapi/task/createServiceTask?"; /** * AccessKey ID and AccessKey secret */ public static final String ACCESS_KEY_ID = System.getenv("RPA_AK_ENV"); public static final String ACCESS_KEY_SECRET = System.getenv("RPA_SK_ENV"); public static void main(String[] args) { // API-specific parameters String httpMethod = "POST"; String appId = "your_app_id"; String clientId = "your_robot_id"; String appParams = "[{\"name\":\"example_param_1\",\"value\":\"example_content_1\"},{\"name\":\"example_param_2\",\"value\":\"example_content_2\"}]"; Map<String, String> specialParams = new HashMap<>(); specialParams.put("appId", appId); specialParams.put("clientId", clientId); specialParams.put("appParams", appParams); // Call example try { Map<String, String> parameters = new HashMap(); // Common request parameters String signatureNonce = UUID.randomUUID().toString(); String timeStamp = formatIso8601Date(new Date()); parameters.put("Version", "20200430"); parameters.put("AccessKeyId", ACCESS_KEY_ID); parameters.put("Timestamp", timeStamp); parameters.put("SignatureMethod", "HMAC-SHA1"); parameters.put("SignatureVersion", "1.0"); parameters.put("SignatureNonce", signatureNonce); parameters.put("Format", "json"); parameters.putAll(specialParams); // Sort the request parameters String[] sortedKeys = parameters.keySet().toArray(new String[]{}); Arrays.sort(sortedKeys); // Construct the stringToSign string StringBuilder stringToSign = new StringBuilder(); stringToSign.append(httpMethod).append("&"); stringToSign.append(percentEncode("/")).append("&"); // Signature parameter StringBuilder canonicalizedQueryString = new StringBuilder(); // Build URL common parameters StringBuilder urlParamsBuild = new StringBuilder(); for (String key : sortedKeys) { // Note: Encode the key and value here. canonicalizedQueryString.append("&") .append(percentEncode(key)).append("=") .append(percentEncode(parameters.get(key))); urlParamsBuild.append("&") .append(percentEncode(key)).append("=") .append(percentEncode(parameters.get(key))); } stringToSign.append(percentEncode( canonicalizedQueryString.substring(1))); // Calculate the signature Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec((ACCESS_KEY_SECRET + "&").getBytes(StandardCharsets.UTF_8), "HmacSHA1")); byte[] signData = mac.doFinal(stringToSign.toString().getBytes(StandardCharsets.UTF_8)); final BASE64Encoder base64Encoder = new BASE64Encoder(); String signature = base64Encoder.encode(signData); String urlReq = urlParamsBuild.substring(1); String url = SERVER + PATH + urlReq + "&Signature=" + percentEncode(signature); String requestResult = restfulReq(url, httpMethod); System.out.println(requestResult); } catch (Exception e) { System.out.println("Encoding failed. Exception: " + e); } } /** * Sends the request */ private static String restfulReq(String url, String method) { Map<String, String> params = new HashMap<>(); String result = ""; try { Map<String, String> header = new HashMap<>(); header.put("contentType", "application/x-www-form-urlencoded;charset=UTF-8"); if ("POST".equals(method)) { result = doPost(url, header, joinParams(params), method); } if ("GET".equals(method)) { result = doGet(url, header, params, method); } } catch (Exception err) { throw new RuntimeException(err.toString()); } return result; } private static String joinParams(Map<String, String> params) { if (params != null) { String result = ""; StringBuilder sb = new StringBuilder(); Iterator<Map.Entry<String, String>> newEntryIt = params.entrySet().iterator(); while (newEntryIt.hasNext()) { Map.Entry<String, String> entry = newEntryIt.next(); sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } if (sb.toString().endsWith("&")) { result = sb.substring(0, sb.length() - 1); } return result; } return null; } /** * Sends a POST request to the specified URL */ private static String doPost(String url, Map<String, String> header, String param, String method) { DataOutputStream out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // Open a connection to the URL HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // Set common request properties conn.setRequestProperty("accept", "*/*"); conn.setRequestMethod(method); Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); conn.setRequestProperty(entry.getKey(), entry.getValue()); } conn.setUseCaches(false); // The following two lines must be set to send a POST request conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(6000); conn.setConnectTimeout(6000); // Define a BufferedReader input stream to read the response from the URL try { if (param != null && !"".equals(param.trim())) { out = new DataOutputStream(conn.getOutputStream()); out.write(param.getBytes()); // Flush the buffer of the output stream out.flush(); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("Exception: " + e); } } catch (Exception e) { System.out.println("Exception: " + e); } // Use a finally block to close the output and input streams finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { System.out.println("Exception-- " + ex.getMessage()); } } return result; } /** * Sends a GET request to the specified URL */ private static String doGet(String urlStr, Map<String, String> header, Map<String, String> params, String method) { URL url; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { // URL input parameters String queryString = ""; if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { queryString += entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "UTF-8") + "&"; } } if (queryString.length() > 0) { queryString = queryString .substring(0, queryString.length() - 1); urlStr = urlStr + "?" + queryString; } url = new URL(urlStr); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(6000); conn.setConnectTimeout(6000); conn.setRequestMethod(method); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("contentType", "application/json;charset=utf-8"); Iterator<Map.Entry<String, String>> it = header.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); conn.setRequestProperty(entry.getKey(), entry.getValue()); } if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { throw new RuntimeException(conn.getResponseCode() + ":" + conn.getResponseMessage()); } } catch (Exception e) { throw new RuntimeException(e.toString()); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { System.out.println("Exception: " + e); } try { if (baos != null) { baos.close(); } } catch (IOException e) { System.out.println("Exception: " + e); } conn.disconnect(); } } private static String percentEncode(String value) throws UnsupportedEncodingException { return value != null ? URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; } private static String formatIso8601Date(Date date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date); } }