You can call Elastic Compute Service (ECS) API operations by sending HTTP or HTTPS requests to the ECS server and obtain responses from the ECS server. When the ECS server receives a request, it verifies the identity of the request sender and validates parameters in the request. After the verification and validation are passed, the ECS server performs required operations based on the parameters specified in the request. Then, the ECS server returns an HTTP response to the request sender.

Components

Each request has the following components:
  • HTTP method: All ECS API operations can be called only by using the GET method.
  • Request URL: A request URL consists of the server URL, the API operation name, custom request parameters, and common request parameters.
  • Server URL: The URL of the ECS server is http://ecs.aliyuncs.com/ or https://ecs.aliyuncs.com/ based on whether the request is sent over HTTP or HTTPS. To ensure the security of requests, we recommend that you send the requests over HTTPS. HTTPS encrypts communications based on the SSL protocol to prevent sensitive information from being leaked due to communication interceptions.
  • API operation name: Each request requires an operation name. You must set the Action parameter to the name of the operation that you want to perform.
  • Custom request parameters: Different request parameters must be set for different operations that you want to call. For more information, see API operation topics.
  • Common request parameters: Common request parameters are required for each operation, such as the TimeStamp parameter and the Signature parameter.
  • Before a request is sent, the request signature must be encoded to ensure that the ECS server can verify the identity of the request sender and authorize the request. For information about how to encode request signatures, see the Request signatures topic.
  • After the request is received by the ECS server, a response is returned. Responses include success responses and error messages. For information about the format of responses, see the Responses topic. The client can parse the response to obtain the operation results.

Example

In this example, the DescribeRegions operation is called.

Set the Action parameter to DescribeRegions. The operation is called to query the most recent region list. No custom request parameters are required in this operation. However, you must add common request parameters to the request URL. Before the Signature parameter is added to the URL, the parameter must be calculated by using signature algorithms. The following code shows the request URL that is not encoded after common request parameters (excluding the Signature parameter) are added:

http://ecs.aliyuncs.com/?TimeStamp=2016-02-23T12:46:24Z&Format=XML&AccessKeyId=testid&Action=DescribeRegions&SignatureMethod=HMAC-SHA1&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2014-05-26&SignatureVersion=1.0

Create a canonicalized query string based on signature calculation rules.

AccessKeyId=testid&Action=DescribeRegions&Format=XML&SignatureMethod=HMAC-SHA1&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&SignatureVersion=1.0&TimeStamp=2016-02-23T12%3A46%3A24Z&Version=2014-05-26

Create a string-to-sign (StringToSign) by encoding the canonicalized query string.

GET&%2F&AccessKeyId%3Dtestid%26Action%3DDescribeRegions%26Format%3DXML%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf%26SignatureVersion%3D1.0%26TimeStamp%3D2016-02-23T12%253A46%253A24Z%26Version%3D2014-05-26

The following Java code shows how to add common request parameters, create a canonicalized query string, and create a string-to-sign (StringToSign). In this example, place all request parameters in a Map <String, String> Java object and set the AccessKey ID to testid.

    final String HTTP_METHOD = "GET";

    Map<String, String> parameters = new HashMap<String, String>();
    // Add request parameters.
    parameters.put("Action", "DescribeRegions");
    parameters.put("Version", "2014-05-26");
    parameters.put("AccessKeyId", "testid");
    parameters.put("TimeStamp", formatIso8601Date(new Date()));
    parameters.put("SignatureMethod", "HMAC-SHA1");
    parameters.put("SignatureVersion", "1.0");
    parameters.put("SignatureNonce", UUID.randomUUID().toString());
    parameters.put("Format", "XML");

    // Sort the parameters.
    String[] sortedKeys = parameters.keySet().toArray(new String[]{});
    Arrays.sort(sortedKeys);

    final String SEPARATOR = "&";

    // Create a string-to-sign
    StringBuilder stringToSign = new StringBuilder();
    stringToSign.append(HTTP_METHOD).append(SEPARATOR);
    stringToSign.append(percentEncode("/")).append(SEPARATOR);

    StringBuilder canonicalizedQueryString = new StringBuilder();
    for(String key : sortedKeys) {
        // Encode the keys and values of the parameters in the Java object.
        canonicalizedQueryString.append("&")
        .append(percentEncode(key)).append("=")
        .append(percentEncode(parameters.get(key)));
    }

    // Encode the canonicalized query string.
    stringToSign.append(percentEncode(
        canonicalizedQueryString.toString().substring(1)));

In this example, the value of the TimeStamp parameter must be specified in the ISO 8601 standard. The time must be in UTC. Otherwise, an error message is returned. The following code shows how to create a string in the specified format for the TimeStamp parameter:

    private static final String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private static String formatIso8601Date(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }

The canonicalized query string (the canonicalizedQueryString variable in the preceding code) and the string-to-sign (SringToSign) must be encoded. For information about encoding rules, see the Request signatures topic. The following code shows the encoding algorithm:

    private static final String ENCODING = "UTF-8";

    private static String percentEncode(String value) throws UnsupportedEncodingException {
        return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null;
    }

In this example, set the AccessKey ID to testid, the AccessKey secret to testsecret, and the key used for calculating the hash-based message authentication code (HMAC) value to testsecret&. The following signature string is obtained:

    CT9X0VtwR86fNWSnsc6v8YGOjuE=

The following Java code shows how to calculate the signature:

    // Calculate the signature.
    final String ALGORITHM = "HmacSHA1";
    final String ENCODING = "UTF-8";
    key = "testsecret&";

    Mac mac = Mac.getInstance(ALGORITHM);
    mac.init(new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM));
    byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING));

    String signature = new String(Base64.encodeBase64(signData));
            

After the Signature parameter is added, encode the request URL based on RFC 3986 to obtain the following URL:

http://ecs.aliyuncs.com/?SignatureVersion=1.0&Action=DescribeRegions&Format=XML&SignatureNonce=3ee8c1b8-83d3-44af-a94f-4e0ad82fd6cf&Version=2014-05-26&AccessKeyId=testid&Signature=CT9X0VtwR86fNWSnsc6v8YGOjuE%3D&SignatureMethod=HMAC-SHA1&TimeStamp=2016-02-23T12%3A46%3A24Z

In this example, send an HTTP request to the preceding URL to obtain the following response from the ECS server:

<DescribeRegionsResponse>
    <Regions>
        <Region>
            <LocalName>China (Qingdao)</LocalName>
            <RegionId>cn-qingdao</RegionId>
        </Region>
        <Region>
            <LocalName>China (Hangzhou)</LocalName>
            <RegionId>cn-hangzhou</RegionId>
        </Region>
    </Regions>
    <RequestId>833C6B2C-E309-45D4-A5C3-03A7A7A48ACF</RequestId>
</DescribeRegionsResponse>
            

After the XML response is returned and parsed, you can obtain the list of available regions, including the RegionId and LocalName values corresponding to the regions. If the Format parameter is set to JSON in the request, the response is returned in the JSON format.