The cloud API is the foundation of Baidu's intelligent cloud opening capability. With the help of the API, you can greatly save labor costs, improve efficiency, and complete the management and control of cloud resources in a more efficient way.For developers, using cloud APIs to complete some repetitive work can greatly save time and energy;In addition, API has the advantages of easy combination, automation, strong scalability, and low requirements for the system.
Maybe you have known about API and HTTP related knowledge concepts, but you just used Baidu intelligent cloud products, and do not know where to start API calls.This article will take you to understand Baidu's intelligent cloud API signature algorithm, andCreate BCC ECS instanceAs an example, let you master the method of calling Baidu Intelligent Cloud API.
This article can be seen as a simplified version of the authentication mechanism document, paying more attention to the process and ignoring some specific requirements and details.If you encounter something you need to know more about in this article, please go toAuthentication and authentication mechanismFor reference.
To call the API, we need to firstGet the structure and parameters of the API requestUnderstand how API requests should be organized and what information they contain;ReconstructionAuthentication string;After the authentication string and other information are filled in each position of the API request as required, the API request can be sent and the response sent back by the server can be received.
Get the structure and parameters of the API request
The whole articleECS BCC creates an instanceFor example, complete a complete API call process.
What is BCC?
ECS BCC (Baidu Cloud Compute) is a scalable computing service of Baidu Intelligent Cloud.The management mode is simpler and more efficient than the physical server. The API can create instances in batches, release any number of ECS instances, and improve the operation and maintenance efficiency.For more details, please refer toBCC API documentation。
To obtain the information needed to call this interface, we must first consult the API documentation of this interface.Log in to Baidu Smart Cloud official website, select "Help and Support>Document" in the top navigation bar, select ECS BCC, and select "API Reference>Instance Related Interfaces>in the left navigation bar of the documentCreate Instance"。
In the interface documentRequest StructureThe section shows us the request method of the API request to be sent, how the URL, request header and request body should be organized, andRequest ParametersIt introduced how to value each variable in the API request.
Parameter position
explain
method
Requested methods, includingPUT、POST、GET、DELETEEtc.The specific method shall be subject to the request structure and request examples in the interface document.
URL absolute path (URL parameter)
Refers to the part separated by/in the whole URL, such as/v2/instance,v2Is the API version number
Query string (Query parameter)
Refers to the whole URL?The rear part.If the query string contains multiple groups of parameters, use&connect.
Request header (header parameter)
Most API requests need to submit some public content (the necessary ones are the service domain name host and the authentication string Authorization. The generation steps of the authentication string are shown belowConstruct authentication string), these contents are uniformly placed in the request header, which is called the public request header.
Request body (RequestBody parameter)
Fill in the parameters of the BCC instance to be created, and the request body uses JSON format
Construct authentication string
Most of the information in the API request only needs you toRequest ParametersThe requirements in can be filled in, which is relatively easy to obtain.However, the authentication string Authorization in the request header needs to use many parameters and be obtained through multiple operations and splicing.
The purpose of authentication string is to verify the identity of the API call initiator, and also to prevent illegal tampering and replay attacks.To generate the authentication string, we need the following information:
Parameter name
Parameter interpretation
accessKeyId
It is called AK for short, which is equivalent to the user name when you call the API. SeeGet AK/SK
SecretAccessKey
Short for SK, which is equivalent to the password when you call the API. SeeGet AK/SK
authStringPrefix
The authentication string prefix is concatenated by/of "bce-auth-v1", {accessKeyId}, {timestamp}, {expirationPeriodInSeconds}.For the value description of the three parameters, seeGenerate authentication string
SigningKey
Obtained by SK and authStringPrefix through HMAC-SHA256-HEX operation
CanonicalRequest
It is composed of the request method, the processed URL absolute path, the processed QueryString, and the processed header using the newline character " n".See details for treatment methodsGenerate canonicalrequest
signature
Obtained by HMAC-SHA256-HEX operation of SigningKey and CanonicalRequest
Authorization
The authentication string is the final result of authentication.It is made of/spliced by authStringPrefix, signedHeaders and signature
signedHeaders
The list of HTTP header domains involved in the signature algorithm, that is, the caller can decide which header domains to include in the signature operation (the host must participate).SeeCanonicalHeaders
To sum up, the process of generating Authorization can be shown in the following figure:
After the authentication string is constructed, put it in the request header to complete the authentication.
The client sends the API request and receives the response
After all the information is ready in the programming environment, you can send the API request.The sending method can refer toComplete API interface calls with Python。
After sending the API, there are two cases:
If the content of the API request is correct, the API interface with a return value will receive the return value information required by the API request;For API interfaces that do not return values, only status codes and response headers will be received, and the response body is empty.
If there is a problem with the API request content, you will receive a response with an error code and error description.You can check all parts of the API request according to the error code to eliminate problems.
Python example explanation
The official website help center provides Python programming signature function methods. The following explanation is to add a request function on the basis of the official website demo to complete calling BCC API to create an instance.
3. Before purchasing an instance, it is necessary to ensure that the account is free of arrears and that the total balance of the account and the available vouchers is greater than or equal to 100 yuan
2. See the API reference document for the data required to create BCC instancesCreate BCC instance
explain:To download the Php example, Java example and Javascript example of the official website demo, please visit the Help Center - "Related Reference -" Authentication Authentication - "Sample Download
Configuration Description
This example uses the specified header_to_sign method for configuration to create BCC instances.
Operation steps
1. In the official website demo example, modules such as requests should be imported to support request functions and idempotent functions.
The functions used in the demo example are: save AK/SK, normalize string, generate standard timestamp, generate standard URI, and generate standard query string.
2. Generate the specification header.
Note:When header_to_sign is not specified, the following five items are used by default to participate in the signature algorithm.
3. The following starts are configured using the specified header_to_sign method.
4. Signature main algorithm module.
Where timestamp=0, expiration_in_seconds=18000, and headers_to_sign=None have given default values.
This example uses a non default configuration. You need to specify header_to_sign. In step 7, complete the splicing of the final signature strings.
5. Use idempotent functions.
It can ensure that the same request is not called repeatedly when BCC is created.
6. Fill in the configuration data in the main project.
The AK, Sk, request method, request path, request header field, idempotence obtained in [Data Preparation] are filled in the main project response parameters.
7. Construct body data.
In the data construction of the body of the request, in order to make the example easy to understand, only the minimum configuration for creating the BCC is used, including instance type, CPU cores, instance name, memory capacity, image ID, payment method, and availability zone.
8. This step is the key point. Specify header_to_sign to participate in the authentication code.
By viewing the request parameters given in the document, select mandatory and partial optional public headers, fill them in the specified header_to_sign, and participate in the authentication code.What needs to be understood here is that the function of the API will not be affected by selecting which headers to encode. However, if too few headers are selected, man in the middle attacks may occur, but the host must be included. For example, the host and x-bce-data are used in this example.
9. Continue to configure the expiration time and timestamp.
The time stamp is the start time of generating the effective authentication. You can take the current time point or the required time point.
10. After the authentication string is constructed and generated, it is added to the authentication field in the header field.
11. Next, construct the request request, splice URL, and initiate the request.
results of enforcement
Now execute a request. In the execution result, the http status is 200, indicating that the BCC instance has been successfully created.You can also view the creation results on Baidu Smart Cloud Console.
Log in to Baidu Smart Cloud Console, select the region Beijing, and you can view the BCC ECS instance just created on the instance list page, which is being created.After the creation is successful, you can use the instance resources.
Subsequent operations
Query BCC Instance
Stop BCC instance
Release BCC instance
On the basis of creating BCC code, the key operations of signature and authentication have been completed. You can call the query, stop and release of BCC instance by yourself according to the data provided by the API document.
Introduce common signature authentication error troubleshooting methods
For more help and support, please fill in your comments on the product API reference document page (as shown below), or submitWork orderconsultation.
Common error codes for API calls
Error code
Error message
HTTP status code
describe
AccessDenied
Access denied.
403Forbidden
No permission to access the corresponding resource.
InappropriateJSON
The JSON you provided was well-formed and valid, but not appropriate forthis operation.
400 Bad Request
The JSON format in the request is correct, but the semantics do not meet the requirements.For example, a required item is missing or the value type does not match.For compatibility reasons, all unrecognized items should be ignored directly and this error should not be returned.
InternalError
We encountered an internal error Please try again.
500 Internal Server Error
All other undefined errors.It should not be used when there are other types of errors (including general and service customized) that have clear corresponding.
InvalidAccessKeyId
The Access Key ID you provided doesnot exist in our records.
403Forbidden
Access Key ID does not exist.
InvalidHTTPAuthHeader
The Access Key ID you provided does notexist in our records.
400 BadRequest
The format of the Authorization header field is incorrect.
InvalidHTTPRequest
There was an error in the body of your HTTP request.
400 Bad Request
The HTTP body format is incorrect.For example, the specified Encoding is not met.
InvalidURI
Could not parse the specified URI.
400 Bad Request
The URI format is incorrect.For example, the keywords of some service definitions do not match.For ID mismatch, more specific error codes should be defined, such as NoSuchKey.
MalformedJSON
The JSON you provided was not well-formed.
400 BadRequest
The JSON format is illegal.
InvalidVersion
The API version specified was invalid.
404 NotFound
The version number of the URI is illegal.
OptInRequired
A subscription for the service is required.
403Forbidden
The corresponding service is not activated.
PreconditionFailed
The specified If-Match header doesn’tmatch the ETag header.
412PreconditionFailed
See Etag for details.
RequestExpired
Request has expired. Timestamp date is <Data>.
400 BadRequest
The request timed out.Change to x-bce-date.If there is only Date in the request, you need to convert Date to datetime.
IdempotentParameterMismatch
The request uses the same client token asa previous, but non-identical request.
403Forbidden
The API parameters corresponding to clientToken are different.
SignatureDoesNotMatch
The request signature we calculated does not match the signature you provided. Check yourSecret Access Key and signing method. Consultthe service documentation for details.
400 Bad Request
The signature attached in the Authorization header field is inconsistent with the server verification.