cvm.tencentcloudapi.com
for CVM) or a specified region (such as cvm.ap-guangzhou.tencentcloudapi.com
for CVM in the Guangzhou region). For values of the region parameter, please see the region list in the "Common Parameters" section below. To check whether a region is supported by a specific Tencent Cloud service, please see its "Request Structure" document.Content-Type
types supported by POST request:Parameter Name | Type | Required | Description |
X-TC-Action | String | Yes | Name of the API for the desired operation. For the specific value, please see the description of common parameter Action in the input parameters in the related API document. For example, the API for querying CVM instance list is DescribeInstances . |
X-TC-Region | String | - | Region parameter, which is used to identify the region where the data you want to manipulate resides. For values supported for an API, please see the description of common parameter Region in the input parameters in related API documentation. Note: this parameter is not required for some APIs (which will be indicated in related API documentation) and will not take effect even if it is passed. |
X-TC-Timestamp | Integer | Yes | The current UNIX timestamp that records the time when the API request was initiated, such as 1529223702. Note: if the difference between the UNIX timestamp and the server time is greater than 5 minutes, a signature expiration error may occur. |
X-TC-Version | String | Yes | Version of the API for the desired operation, such as 2017-03-12 for CVM. For the specific value, please see the description of common parameter Version in the input parameters in related API documentation. |
Authorization | String | Yes | HTTP authentication request header, such as TC3-HMAC-SHA256 Credential=AKIDEXAMPLE/Date/service/tc3_request, SignedHeaders=content-type;host, Signature=72e494ea8******************************************a96525168 Here, TC3-HMAC-SHA256: signature algorithm, currently fixed as this value. Credential: signature credential. AKIDEXAMPLE indicates the SecretId . Date indicates a UTC date which must match the value of X-TC-Timestamp (a common parameter) in UTC format. service indicates the name of the service and is generally a domain name prefix; for example, the domain name cvm.tencentcloudapi.com means the CVM service, and the value for this service is cvm . SignedHeaders: the headers that contain the authentication information. content-type and host are required. Signature: signature digest. For the calculation process, please see below. |
X-TC-Token | String | No | Token used for temporary credentials. It must be used with a temporary key. You can get the temporary key and token by calling a CAM API. No token is required for a long-term key. |
Parameter Name | Type | Required | Description |
Action | String | Yes | Name of the API for the desired operation. For the specific value, please see the description of common parameter Action in the input parameters in the related API document. For example, the API for querying CVM instance list is DescribeInstances . |
Region | String | - | Region parameter, which is used to identify the region where the data you want to manipulate resides. For values supported for an API, please see the description of common parameter Region in the input parameters in related API documentation. Note: this parameter is not required for some APIs (which will be indicated in related API documentation) and will not take effect even if it is passed. |
Timestamp | Integer | Yes | The current UNIX timestamp that records the time when the API request was initiated, such as 1529223702. If the difference between the UNIX timestamp and the current time is too large, a signature expiration error may occur. |
Nonce | Integer | Yes | A random positive integer used in conjunction with Timestamp to prevent replay attacks. |
SecretId | String | Yes | The identifying SecretId obtained on the TencentCloud API Key page. A SecretId corresponds to a unique SecretKey which is used to generate the request signature (Signature ). |
Signature | String | Yes | Request signature, which is used to verify the validity of the request. It is generated based on input parameters. For more information on how to calculate the signature, please see below. |
Version | String | Yes | Version of the API for the desired operation, such as 2017-03-12 for CVM. For the specific value, please see the description of common parameter Version in the input parameters in related API documentation. |
SignatureMethod | String | No | Signature algorithm. Currently, only HmacSHA256 and HmacSHA1 are supported. The HmacSHA256 algorithm is used to verify the signature only when this parameter is specified as HmacSHA256. In other cases, the signature is verified with HmacSHA1. |
Token | String | No | Token used for temporary credentials. It must be used with a temporary key. You can get the temporary key and token by calling a CAM API. No token is required for a long-term key. |
SecretId
and SecretKey
are AKIDz8krbsJ5**********mLPx3EXAMPLE
and Gu5t9xGAR***********EXAMPLE
, respectively. If you want to view the status of an unnamed instance in the Guangzhou region and have only one data entry returned, the request may be: curl -X POST https://cvm.tencentcloudapi.com \\-H "Authorization: TC3-HMAC-SHA256 Credential=AKIDz8krbsJ5**********mLPx3EXAMPLE/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=72e494ea809ad7a8c8f7a4507b9bddcbaa8e581f516e8da2f66e2c5a96525168" \\-H "Content-Type: application/json; charset=utf-8" \\-H "Host: cvm.tencentcloudapi.com" \\-H "X-TC-Action: DescribeInstances" \\-H "X-TC-Timestamp: 1551113065" \\-H "X-TC-Version: 2017-03-12" \\-H "X-TC-Region: ap-guangzhou" \\-d '{"Limit": 1, "Filters": [{"Values": ["\\u672a\\u547d\\u540d"], "Name": "instance-name"}]}'
SecretId
and a SecretKey
. Each user can have up to two key pairs.Content-Type: application/x-www-form-urlencoded
protocol format is supported. For the POST method, Content-Type: application/json
and Content-Type: multipart/form-data
are supported. The JSON format is supported by all business APIs, while the multipart format is supported only by specific APIs (in this case, an API cannot be called in JSON format). For more information, please see the specific business API document. We recommend you use the POST method because the two methods generate the same results, but the GET method only supports request packets below 32 KB in size.CanonicalRequest =HTTPRequestMethod + '\\n' +CanonicalURI + '\\n' +CanonicalQueryString + '\\n' +CanonicalHeaders + '\\n' +SignedHeaders + '\\n' +HashedRequestPayload
Field | Description |
HTTPRequestMethod | HTTP request method (GET or POST). This example uses POST . |
CanonicalURI | URI parameter. Slash ("/") is used for API 3.0. |
CanonicalQueryString | Query string in the URL of the originating HTTP request. This is always an empty string "" for POST requests and is the string after the question mark (?) for GET requests such as Limit=10&Offset=0 . Note: CanonicalQueryString must be URL-encoded as instructed in RFC 3986 with the UTF-8 character set. The applicable standard programming language library is recommended. All special characters must be encoded and capitalized. |
CanonicalHeaders | Header information for signature calculation, including at least host and content-type . Custom headers can also be added to the signature process to improve the uniqueness and security of the request. Concatenation rules: both the key and value of a header should be converted to lowercase with the leading and trailing spaces removed so that they are concatenated in the key:value\\n format. If there are multiple headers, they should be sorted in ASCII ascending order by header key (lowercase). The calculation result in this example is content-type:application/json; charset=utf-8\\nhost:cvm.tencentcloudapi.com\\n . Note: content-type must match the content that is actually sent. In some programming languages, a charset value is automatically added even if it is not specified. In this case, the request sent will be different from the one signed, and the sever will return a signature verification failure. |
SignedHeaders | Header information for signature calculation, indicating the request headers that are involved in the signature process. The request headers must correspond to the headers in CanonicalHeaders . Content-type and host are required headers. Concatenation rules: both the key and value of a header should be converted to lowercase. If there are multiple headers, they should be sorted in ASCII ascending order by header key (lowercase) and separated by semicolons (;). The value in this example is content-type;host . |
HashedRequestPayload | Hash value of Requestpayload (i.e., the request body, such as {"Limit": 1, "Filters": [{"Values": ["\\u672a\\u547d\\u540d"], "Name": "instance-name"}]} in this example). The pseudo-code for calculation is Lowercase(HexEncode(Hash.SHA256(RequestPayload))) , which means that SHA256 hashing is performed on the payload of the HTTP request, then hexadecimal encoding is performed, and finally the encoded string is converted to lowercase letters. For GET requests, RequestPayload is always an empty string. The calculation result in this example is 35e9c5b0e3ae67532d3c9f17ead6c90222632e5b1ff7f6e89887f1398934f064 . |
POST/content-type:application/json; charset=utf-8host:cvm.tencentcloudapi.comcontent-type;host35e9c5b0e3ae67532d3c9f17ead6c90222632e5b1ff7f6e89887f1398934f064
StringToSign =Algorithm + \\n +RequestTimestamp + \\n +CredentialScope + \\n +HashedCanonicalRequest
Field | Description |
Algorithm | Signature algorithm, which is always TC3-HMAC-SHA256 currently. |
RequestTimestamp | Request timestamp, i.e., the value of the common parameter X-TC-Timestamp in the request header. It is the UNIX timestamp of the current time in seconds, such as 1551113065 in this example. |
CredentialScope | Scope of the credential in the format of Date/service/tc3_request , including the date, requested service, and termination string (tc3_request). Date indicates a UTC date, which should match the UTC date converted by the common parameter X-TC-Timestamp .service is the service name, which should match the domain name of the service called. The calculation result in this example is 2019-02-25/cvm/tc3_request . |
HashedCanonicalRequest | Hash value of the canonical request string concatenated in the steps above. The pseudo-code for calculation is Lowercase(HexEncode(Hash.SHA256(CanonicalRequest))) . The calculation result in this example is 5ffe6a04c0664d6b969fab9a13bdab201d63ee709638e2749d62a09ca18d7031 . |
Date
must be calculated from the timestamp X-TC-Timestamp
and the time zone is UTC+0. If you add the local time zone information (such as UTC+8) in the system, calls can succeed both day and night but will definitely fail at 00:00. For example, if the timestamp is 1551113065 and the time in UTC+8 is 2019-02-26 00:44:25, the UTC+0 date in the calculated Date
value should be 2019-02-25 instead of 2019-02-26.Timestamp
must be the same as your current system time, and your system time must be in sync with the UTC time. If the difference between the timestamp and your current system time is greater than five minutes, the request will fail. If your system time is out of sync with the UTC time for a prolonged period, the request will fail, and a signature expiration error will be returned.TC3-HMAC-SHA25615511130652019-02-25/cvm/tc3_request5ffe6a04c0664d6b969fab9a13bdab201d63ee709638e2749d62a09ca18d7031
SecretKey = "Gu5t9xGARN**********QYCN3EXAMPLE"SecretDate = HMAC_SHA256("TC3" + SecretKey, Date)SecretService = HMAC_SHA256(SecretDate, Service)SecretSigning = HMAC_SHA256(SecretService, "tc3_request")
Field | Description |
SecretKey | Original SecretKey , i.e., Gu5t9xGARN**********QYCN3EXAMPLE . |
Date | Value of the Date field in Credential , such as 2019-02-25 in this example. |
Service | Value of the Service field in Credential , such as cvm in this example. |
Signature = HexEncode(HMAC_SHA256(SecretSigning, StringToSign))
72e494ea8*******************************c5a96525168
. Authorization
string in the following format: Authorization =Algorithm + ' ' +'Credential=' + SecretId + '/' + CredentialScope + ', ' +'SignedHeaders=' + SignedHeaders + ', ' +'Signature=' + Signature
Field | Description |
Algorithm | Signature algorithm, which is always TC3-HMAC-SHA256 . |
SecretId | SecretId in the key pair, i.e., AKIDz8krbsJ5yK**********mLPx3EXAMPLE . |
CredentialScope | Credential scope (see above). The calculation result in this example is 2019-02-25/cvm/tc3_request . |
SignedHeaders | Header information for signature calculation (see above), such as content-type;host in this example. |
Signature | Signature value. The calculation result in this example is 72e494ea809ad7a8c8f7a450***************f516e8da2f66e2c5a96525168 . |
TC3-HMAC-SHA256 Credential=AKIDz8krbsJ5yK**********mLPx3EXAMPLE/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=72e494ea809ad7a8c8f7a450***************f516e8da2f66e2c5a96525168
POST https://cvm.tencentcloudapi.com/Authorization: TC3-HMAC-SHA256 Credential=AKIDz8krbsJ5yK**********mLPx3EXAMPLE/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=72e494ea809ad7a8c8f7a450***************f516e8da2f66e2c5a96525168Content-Type: application/json; charset=utf-8Host: cvm.tencentcloudapi.comX-TC-Action: DescribeInstancesX-TC-Version: 2017-03-12X-TC-Timestamp: 1551113065X-TC-Region: ap-guangzhou{"Limit": 1, "Filters": [{"Values": ["\\u672a\\u547d\\u540d"], "Name": "instance-name"}]}
# -*- coding: utf-8 -*-import hashlib, hmac, json, os, sys, timefrom datetime import datetime# Key parametersecret_id = "`AKIDz8krbsJ5yK**********mLPx3EXAMPLE`"secret_key = "`Gu5t9xGARN**********QYCN3EXAMPLE`"service = "cvm"host = "cvm.tencentcloudapi.com"endpoint = "https://" + hostregion = "ap-guangzhou"action = "DescribeInstances"version = "2017-03-12"algorithm = "TC3-HMAC-SHA256"#timestamp = int(time.time())timestamp = 1551113065date = datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d")params = {"Limit": 1, "Filters": [{"Name": "instance-name", "Values": [u"unnamed"]}]}# ************* Step 1. Concatenate the canonical request string *************http_request_method = "POST"canonical_uri = "/"canonical_querystring = ""ct = "application/json; charset=utf-8"payload = json.dumps(params)canonical_headers = "content-type:%s\\nhost:%s\\n" % (ct, host)signed_headers = "content-type;host"hashed_request_payload = hashlib.sha256(payload.encode("utf-8")).hexdigest()canonical_request = (http_request_method + "\\n" +canonical_uri + "\\n" +canonical_querystring + "\\n" +canonical_headers + "\\n" +signed_headers + "\\n" +hashed_request_payload)print(canonical_request)# ************* Step 2. Concatenate the string to sign *************credential_scope = date + "/" + service + "/" + "tc3_request"hashed_canonical_request = hashlib.sha256(canonical_request.encode("utf-8")).hexdigest()string_to_sign = (algorithm + "\\n" +str(timestamp) + "\\n" +credential_scope + "\\n" +hashed_canonical_request)print(string_to_sign)# ************* Step 3. Calculate the signature *************# Function for calculating signature digestdef sign(key, msg):return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()secret_date = sign(("TC3" + secret_key).encode("utf-8"), date)secret_service = sign(secret_date, service)secret_signing = sign(secret_service, "tc3_request")signature = hmac.new(secret_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()print(signature)# ************* Step 4. Concatenate the `Authorization` string *************authorization = (algorithm + " " +"Credential=" + secret_id + "/" + credential_scope + ", " +"SignedHeaders=" + signed_headers + ", " +"Signature=" + signature)print(authorization)print('curl -X POST ' + endpoint+ ' -H "Authorization: ' + authorization + '"'+ ' -H "Content-Type: application/json; charset=utf-8"'+ ' -H "Host: ' + host + '"'+ ' -H "X-TC-Action: ' + action + '"'+ ' -H "X-TC-Timestamp: ' + str(timestamp) + '"'+ ' -H "X-TC-Version: ' + version + '"'+ ' -H "X-TC-Region: ' + region + '"'+ " -d '" + payload + "'")
DescribeInstances
API to query CVM instances, the request parameters may be as follows:Parameter Name | Description | Value |
Action | Method | DescribeInstances |
SecretId | Key ID | AKIDz8krbsJ5**********mLPx3EXAMPLE |
Timestamp | Current timestamp | 1465185768 |
Nonce | Random positive integer | 11886 |
Region | Instance region | ap-guangzhou |
InstanceIds.0 | ID of the instance to be queried | ins-09dx96dg |
Offset | Offset | 0 |
Limit | Allowed maximum number of output entries | 20 |
Version | API version number | 2017-03-12 |
InstanceIds.2
should be arranged behind InstanceIds.12
. You can complete sorting by using a sorting function in a programming language, such as the ksort
function in PHP.{'Action' : 'DescribeInstances','InstanceIds.0' : 'ins-09dx96dg','Limit' : 20,'Nonce' : 11886,'Offset' : 0,'Region' : 'ap-guangzhou','SecretId' : 'AKIDz8krbsJ5**********mLPx3EXAMPLE','Timestamp' : 1465185768,'Version': '2017-03-12',}
parameter=value
. For example, for the Action
parameter, its parameter is Action
and its value is DescribeInstances
; therefore, the parameter will be formatted into Action=DescribeInstances
.value
is the original value instead of the URL-encoded value.&
. The generated request string will be as follows:Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Limit=20&Nonce=11886&Offset=0&Region=ap-guangzhou&SecretId=AKIDz8krbsJ5**********mLPx3EXAMPLE&Timestamp=1465185768&Version=2017-03-12
/
.request method + request server + request path + ? + request string
.GETcvm.tencentcloudapi.com/?Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Limit=20&Nonce=11886&Offset=0&Region=ap-guangzhou&SecretId=AKIDz8krbsJ5**********mLPx3EXAMPLE&Timestamp=1465185768&Version=2017-03-12
secret_key = "Gu5t9xGAR********QYCN3EXAMPLE"s = "GETcvm.tencentcloudapi.com/?Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Limit=20&Nonce=11886&Offset=0&Region=ap-guangzhou&SecretId=AKIDz8krbsJ5yK**********mLPx3EXAMPLE&Timestamp=1465185768&Version=2017-03-12"hmac_str = hmac.new(secret_key.encode("utf8"), s.encode("utf8"),hashlib.sha1).digest()# Final signature stringSignature = base64.b64encode(hmac_str)
data["Signature"] = base64.b64encode(hmac_str)print(data["Signature"]) # Final signature string# The API will be called actually, and fees may be incurred if the call is successfulresp = requests.get("https://" + endpoint, params=data)print(resp.url)
Field | Description |
endpoint | Service address, such as cvm.tencentcloudapi.com . |
data | API parameter of the sample API 3.0 signature v1. Note: you should add the calculated signature in the format of key-value pair to data . |
curl
, an authentication error The signature expired
will be returned. To obtain a URL that works, you need to replace the SecretId
and SecretKey
in this example with your own credentials and use the current system time as the Timestamp
.Eli*****************cGeI=
, the final value of the Signature
request parameter will be EliP***********************eI%3D
, which will be used to generate the final request URL.Content-Type
of application/x-www-form-urlencoded
, all the request parameter values must be URL-encoded (except the parameter key and the equal symbol (=)) before the request is sent. Non-ASCII characters must be encoded with UTF-8 before URL-encoding.requests
dependency package must be installed first by running pip install requests
.# -*- coding: utf8 -*-import base64import hashlibimport hmacimport timeimport requestssecret_id = "AKIDz8k*********LPx3EXAMPLE"secret_key = "Gu5t9xGA*********YCN3EXAMPLE"def get_string_to_sign(method, endpoint, params):s = method + endpoint + "/?"query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params))return s + query_strdef sign_str(key, s, method):hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest()return base64.b64encode(hmac_str)if __name__ == '__main__':endpoint = "cvm.tencentcloudapi.com"data = {'Action' : 'DescribeInstances','InstanceIds.0' : 'ins-09dx96dg','Limit' : 20,'Nonce' : 11886,'Offset' : 0,'Region' : 'ap-guangzhou','SecretId' : secret_id,'Timestamp' : 1465185768, # int(time.time())'Version': '2017-03-12'}s = get_string_to_sign("GET", endpoint, data)data["Signature"] = sign_str(secret_key, s, hashlib.sha1)print(data["Signature"])# The API will be called actually, and fees may be incurred if the call is successful# resp = requests.get("https://" + endpoint, params=data)# print(resp.url)
Error Code | Error Description |
AuthFailure.SignatureExpire | The signature expired. The difference between the Timestamp and the server time cannot be greater than five minutes. |
AuthFailure.SecretIdNotFound | The key does not exist. Log in to the console and check whether it is disabled or you copied fewer or more characters. |
AuthFailure.SignatureFailure | Signature error. It is possible that the signature is calculated incorrectly, the signature does not match the content that is actually sent, or the SecretKey is incorrect. |
AuthFailure.TokenFailure | Temporary credential token error. |
AuthFailure.InvalidSecretId | Invalid key (not TencentCloud API key type). |
DescribeInstancesStatus
(version: 2017-03-12) to view the status of instances, if the request succeeds, you may see the following response:{"Response": {"TotalCount": 0,"InstanceStatusSet": [],"RequestId": "b5b41468-520d-4192-b42f-595cc34b6c1c"}}
Response
, which contains RequestId
, as long as it processes the request, no matter whether the request is successful or not.RequestId
is the unique ID of an API request. It is required to troubleshoot issues.TotalCount
and InstanceStatusSet
are specific to the DescribeInstancesStatus
API. Since the user who initiated the request does not have a CVM instance yet, 0 is returned for TotalCount
and InstanceStatusSet
is empty.{"Response": {"Error": {"Code": "AuthFailure.SignatureFailure","Message": "The provided credentials could not be validated. Please check your signature is correct."},"RequestId": "ed93f3cb-f35e-473f-b9f3-0d451b8b79c6"}}
Error
indicates that the request failed. A response for a failed request will always include the Error
, Code
, and Message
fields.Code
indicates the specific error code, which is returned when an API request failed. You can use this code to locate the cause and solution of the error in the common or API-specific error code list.Message
explains the cause of the error. Note that the returned messages are subject to service updates. The information the messages provide may not be up-to-date and should not be the only source of reference.RequestId
is the unique ID of an API request. It is required to troubleshoot issues.Error
field in a response indicates that the API call failed. The Code
field in Error
indicates the error code. The following table lists the common error codes that any services may return.Error Code | Error Description |
AuthFailure.InvalidSecretId | Invalid key (not TencentCloud API key type). |
AuthFailure.MFAFailure | MFA failure. |
AuthFailure.SecretIdNotFound | The key does not exist. |
AuthFailure.SignatureExpire | The signature expired. |
AuthFailure.SignatureFailure | Signature error. |
AuthFailure.TokenFailure | Token error. |
AuthFailure.UnauthorizedOperation | No CAM authorization. |
DryRunOperation | DryRun Operation. It means that the request would have succeeded, but the DryRun parameter was used. |
FailedOperation | The operation failed. |
InternalError | Internal error. |
InvalidAction | The API does not exist. |
InvalidParameter | Incorrect parameter. |
InvalidParameterValue | Invalid parameter value. |
LimitExceeded | The quota limit is exceeded. |
MissingParameter | A parameter is missing. |
NoSuchVersion | The API version does not exist. |
RequestLimitExceeded | The request rate limit is exceeded. |
ResourceInUse | The resource is in use. |
ResourceInsufficient | Insufficient resource. |
ResourceNotFound | The resource does not exist. |
ResourceUnavailable | The resource is unavailable. |
UnauthorizedOperation | Unauthorized operation. |
UnknownParameter | Unknown parameter error. |
UnsupportedOperation | Unsupported operation. |
UnsupportedProtocol | Unsupported HTTPS request method. Only GET and POST requests are supported. |
UnsupportedRegion | Unsupported region. |
Was this page helpful?