Access Authenticated Using an AK/SK
If a real-time service is in the Running state, the real-time service has been deployed successfully. This service provides a standard RESTful API for users to call. Users can call the API using AK/SK-based authentication.
When AK/SK-based authentication is used, you can use the APIG SDK or ModelArts SDK to access APIs. For details, see Overview of Session Authentication. This section describes how to use the APIG SDK to access a real-time service. The process is as follows:
- Obtaining an AK/SK Pair
- Obtaining Information About a Real-Time Service
- Sending an Inference Request
- AK/SK-based authentication supports API requests with a body not larger than 12 MB. For API requests with a larger body, token-based authentication is recommended.
- The local time on the client must be synchronized with the clock server to avoid a large offset in the value of the X-Sdk-Date request header. API Gateway checks the time format and compares the time with the time when API Gateway receives the request. If the time difference exceeds 15 minutes, API Gateway will reject the request.
Obtaining an AK/SK Pair
If an AK/SK pair is already available, skip this step. Find the downloaded AK/SK file, which is usually named credentials.csv.
As shown in the following figure, the file contains the username, AK, and SK.
- Register with and log in to the management console.
- Click the username and choose My Credentials from the drop-down list.
- On the My Credentials page, choose Access Keys in the navigation pane.
- Click Create Access Key. The Identity Verification dialog box is displayed.
- Complete the identity authentication as prompted, download the access key, and keep it secure.
Obtaining Information About a Real-Time Service
When calling an API, you need to obtain the API address and input parameters of the real-time service. The procedure is as follows:
- Log in to the ModelArts management console. In the left navigation pane, choose Service Deployment > Real-Time Services. By default, the system switches to the Real-Time Services page.
- Click the name of the target service. The service details page is displayed.
- On the details page of a real-time service, obtain the API address and input parameters of the service.
The API URL is the service URL of the real-time service. If a path is defined for apis in the model configuration file, the URL must be followed by the user-defined path, for example, {URL of the real-time service}/predictions/poetry.Figure 2 Obtaining the API URL and file prediction input parameters of a real-time service
Figure 3 Obtaining the API URL and text prediction input parameters of a real-time service
Method 1: Use Python to Send an Inference Request
- Download the Python SDK and configure it in the development tool. For details, see Integrating the Python SDK for API request signing.
- Create a request body for inference.
- File input
# coding=utf-8 import requests import os from apig_sdk import signer if __name__ == '__main__': # Config url, ak, sk and file path. url = "URL of the real-time service" # Hardcoded or plaintext AK/SK is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. # In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. ak = os.environ["HUAWEICLOUD_SDK_AK"] sk = os.environ["HUAWEICLOUD_SDK_SK"] file_path = "Local path to the inference file" # Create request, set method, url, headers and body. method = 'POST' headers = {"x-sdk-content-sha256": "UNSIGNED-PAYLOAD"} request = signer.HttpRequest(method, url, headers) # Create sign, set the AK/SK to sign and authenticate the request. sig = signer.Signer() sig.Key = ak sig.Secret = sk sig.Sign(request) # Send request files = {'images': open(file_path, 'rb')} resp = requests.request(request.method, request.scheme + "://" + request.host + request.uri, headers=request.headers, files=files) # Print result print(resp.status_code) print(resp.text)
file_path is the local path to the inference file. The path can be an absolute path (for example, D:/test.png for Windows and /opt/data/test.png for Linux) or a relative path (for example, ./test.png).
Request body format of files: files = {"Request parameter": ("Load path", File content, "File type")}. For details about parameters of files, see Table 1.Table 1 Parameters of files Parameter
Mandatory
Description
Request parameter
Yes
Enter the parameter name of the real-time service.
Load path
No
Path in which the file is stored.
File content
Yes
Content of the file to be uploaded.
File type
No
Type of the file to be uploaded, which can be one of the following options:
- txt: text/plain
- jpg/jpeg: image/jpeg
- png: image/png
- Text input (JSON)
The following is an example of the request body for reading the local inference file and performing Base64 encoding:
# coding=utf-8 import base64 import json import os import requests from apig_sdk import signer if __name__ == '__main__': # Config url, ak, sk and file path. url = "URL of the real-time service" # Hardcoded or plaintext AK/SK is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. # In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. ak = os.environ["HUAWEICLOUD_SDK_AK"] sk = os.environ["HUAWEICLOUD_SDK_SK"] file_path = "Local path to the inference file" with open(file_path, "rb") as file: base64_data = base64.b64encode(file.read()).decode("utf-8") # Create request, set method, url, headers and body. method = 'POST' headers = { 'Content-Type': 'application/json' } body = { 'image': base64_data } request = signer.HttpRequest(method, url, headers, json.dumps(body)) # Create sign, set the AK/SK to sign and authenticate the request. sig = signer.Signer() sig.Key = ak sig.Secret = sk sig.Sign(request) # Send request resp = requests.request(request.method, request.scheme + "://" + request.host + request.uri, headers=request.headers, data=request.body) # Print result print(resp.status_code) print(resp.text)
The body name is determined by the input parameter of the real-time service. The parameter name must be the same as that of the input parameter of the string type. image is used as an example. The value of base64_data in body is of the string type.
- File input
Method 2: Use Java to Send an Inference Request
- Download the Java SDK and configure it in the development tool.
- Create a Java request body for inference.
In the APIG Java SDK, request.setBody() can only be a string. Therefore, only text inference requests are supported. If a file is input, convert the file into text using Base64.
- File input
The following is an example of the request body (JSON) for reading the local inference file and performing Base64 encoding.
package com.apig.sdk.demo; import com.cloud.apigateway.sdk.utils.Client; import com.cloud.apigateway.sdk.utils.Request; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class MyAkSkTest2 { public static void main(String[] args) { String url = "URL of the real-time service"; // Hard-coded or plaintext AK/SK is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); String filePath = "Local path to the inference file"; try { // Create request Request request = new Request(); // Set the AK/SK to sign and authenticate the request. request.setKey(ak); request.setSecret(sk); // Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH. request.setMethod(HttpPost.METHOD_NAME); // Add header parameters request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // Set a request URL in the format of https://{Endpoint}/{URI}. request.setUrl(url); // build your json body String body = "{\"image\":\"" + getBase64FromFile(filePath) + "\"}"; // Special characters, such as the double quotation mark ("), contained in the body must be escaped. request.setBody(body); // Sign the request. HttpRequestBase signedRequest = Client.sign(request); // Send request. CloseableHttpResponse response = HttpClients.createDefault().execute(signedRequest); // Print result System.out.println(response.getStatusLine().getStatusCode()); System.out.println(EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } } /** * Convert the file into a byte array and Base64 encode it * @return */ private static String getBase64FromFile(String filePath) { // Convert the file into a byte array InputStream in = null; byte[] data = null; try { in = new FileInputStream(filePath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // Base64 encode return new String(Base64.encodeBase64(data)); } }
If Base64 encoding is used, you need to add the code for decoding the request body to the model inference code.
- Text input (JSON)
// Package name of the demo. package com.apig.sdk.demo; import com.cloud.apigateway.sdk.utils.Client; import com.cloud.apigateway.sdk.utils.Request; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class MyAkSkTest { public static void main(String[] args) { String url = "URL of the real-time service"; // Hard-coded or plaintext AK/SK is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); try { // Create request Request request = new Request(); // Set the AK/SK to sign and authenticate the request. request.setKey(ak); request.setSecret(sk); // Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH. request.setMethod(HttpPost.METHOD_NAME); // Add header parameters request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); // Set a request URL in the format of https://{Endpoint}/{URI}. request.setUrl(url); // Special characters, such as the double quotation mark ("), contained in the body must be escaped. String body = "{}"; request.setBody(body); // Sign the request. HttpRequestBase signedRequest = Client.sign(request); // Send request. CloseableHttpResponse response = HttpClients.createDefault().execute(signedRequest); // Print result System.out.println(response.getStatusLine().getStatusCode()); System.out.println(EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } } }
body is determined by the text format. JSON is used as an example.
- File input
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot