Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Access Authenticated Using an AK/SK

Updated on 2025-01-06 GMT+08:00

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:

  1. Obtaining an AK/SK Pair
  2. Obtaining Information About a Real-Time Service
  3. Sending an Inference Request
NOTE:
  1. 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.
  2. 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.

Figure 1 Content of the credential.csv file
Perform the following operations to generate an AK/SK pair:
  1. Register with and log in to the management console.
  2. Click the username and choose My Credentials from the drop-down list.
  3. On the My Credentials page, choose Access Keys in the navigation pane.
  4. Click Create Access Key. The Identity Verification dialog box is displayed.
  5. 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:

  1. 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.
  2. Click the name of the target service. The service details page is displayed.
  3. 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

  1. Download the Python SDK and configure it in the development tool. For details, see Integrating the Python SDK for API request signing.
  2. 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.

Method 2: Use Java to Send an Inference Request

  1. Download the Java SDK and configure it in the development tool.
  2. 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));
          }
      }
      CAUTION:

      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.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback