API call examples
This topic provides Python and Java examples for calling the CreateTask API of a service robot. For details on constructing HTTP request parameters for API calls, see HTTP Calling Instructions.
Configure access credentials
Before calling an API, configure environment variables to store your access credentials.
For Robotic Process Automation (RPA), the environment variable names for AccessKeyId and AccessSecret are RPA_AK_ENV and RPA_SK_ENV.
Configuration for Linux and macOS
Run the following commands:
export RPA_AK_ENV=<your_AccessKeyId>
export RPA_SK_ENV=<your_AccessSecret>
Configuration for Windows
Right-click My Computer and select Properties.
In the window that appears, click 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 AccessKeyId and AccessSecret from the system settings page of the RPA console.
Restart your computer.
Code 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 CreateTask API. # The access 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_application_id" clientId = "your_robot_id" appParams = json.dumps([{"name": "example_param_1", "value": "example_value_1"}, {"name": "example_param_2", "value": "example_value_2"}]) params = {"AccessKeyId": AccessKeyId, "Format": data_format, "SignatureMethod": signature_method, "SignatureNonce": signature_nonce, "SignatureVersion": signature_version, "Timestamp": timestamp, "Version": version, "AppId": appId, "AllocateMode": 'manu', "RobotId": clientId, "AppParams": appParams, } # print(params) # Parameters for signature calculation: access secret, request method, common request parameters, and API-specific parameters. # Step 1: Sort the common and API-specific request parameters alphabetically. items = list(params.keys()) items.sort() temp_list = [] for i in items: # The AppParams parameter in the CreateTask API requires a serialized JSON array, which needs special handling during the signing process. # For other APIs with complex parameters (e.g., InitInfo in the AddRobot API), you must add corresponding conditions. 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. h = hmac.new((AccessSecret + '&').encode("utf-8"), StringToSign.encode("utf-8"), sha1).digest() Signature = base64.b64encode(h) # Print the signature. # print(Signature) # The Timestamp and SignatureNonce values used for signing are also required in the request. # print(timestamp) # print(signature_nonce) # Create a service robot task. url = 'https://console-rpa.aliyun.com/rpa/openapi/raas/task/CreateTask' 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 { /** * The server address. This example uses the address of an RPA public cloud cluster. */ public static final String SERVER = "https://console-rpa.aliyun.com"; /** * The API endpoint. The CreateTask API is used in this example. */ public static final String PATH = "/rpa/openapi/raas/task/CreateTask?"; /** * AccessKeyId and AccessKeySecret */ 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_application_id"; // The robot allocation mode. The default value is 'auto' for automatic allocation. To assign a specific robot, set AllocateMode to 'manu'. String allocateMode = "manu"; String robotId = "your_robot_id"; // Required when allocateMode is "manu". String appParams = "[{\"name\":\"example_param_1\",\"value\":\"example_value_1\"},{\"name\":\"example_param_2\",\"value\":\"example_value_2\"}]"; Map<String, String> specialParams = new HashMap<>(); specialParams.put("AppId", appId); specialParams.put("AllocateMode", allocateMode); specialParams.put("RobotId", robotId); specialParams.put("AppParams", appParams); // Example call 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 string to be signed. StringBuilder stringToSign = new StringBuilder(); stringToSign.append(httpMethod).append("&"); stringToSign.append(percentEncode("/")).append("&"); // Signature parameters StringBuilder canonicalizedQueryString = new StringBuilder(); // Build the request parameter string. StringBuilder urlParamsBuild = new StringBuilder(); for (String key : sortedKeys) { // Note: The key and value must be encoded. 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 are required for POST requests. conn.setDoOutput(true); conn.setDoInput(true); conn.setReadTimeout(6000); conn.setConnectTimeout(6000); // Read the URL response. try { if (param != null && !"".equals(param.trim())) { out = new DataOutputStream(conn.getOutputStream()); out.write(param.getBytes()); // Flush the output stream buffer. 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); } // 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 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); } }