Invoking EnOS APIs Using EnOS SDKs


This tutorial will guide you in your first EnOS API request using EnOS SDKs, with the help of examples.

Prerequisites


Before calling EnOS APIs, ensure that you have obtained an application service account and assigned API calling permissions and resource access permissions to the application. For more details, refer to API Authentication.

Using Java SDK


To invoke EnOS APIs using Java SDK, you need to install the Java Core SDK (Poseidon). Poseidon supports Java 7 and onwards.

Installation Method

Java core SDK (Poseidon)


Open the EnOS SDKs & Tools, download the installation package, and import it to your development environment. If your application uses the pom project, add the following dependencies to the pom.xml file (you may need to change the version number):

<dependency>
  <groupId>com.enos-iot</groupId>
  <artifactId>apim-poseidon</artifactId>
  <version>0.2.4</version>
</dependency>

Request Method

Synchronous Request


  1. For the GET method, if the API logging feature is disabled, only the result is returned after calling the API. The sample code is as follows:

    Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey))
         .url("https://{apigw-address}/{service-name}/{api-version}/{api_name}?{param1=value1&param2=value2}")
         .method("GET")
         .sync();
    


  2. For the GET method, if the API logging feature is enabled, both the request parameters with time stamp and response are returned after calling the API. The sample code is as follows:

    Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey).debug())
         .url("https://{apigw-address}/{service-name}/{api-version}/{api_name}?{param1=value1&param2=value2}")
         .method("GET")
         .sync();
    


  3. For the GET method, supports independent path setting. The sample code is as follows:

    Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey).debug())
                .url("https://{apigw-address}")
                .path("/{service-name}/{api-version}/{api_name}")
                .method("GET")
                .header("")
                .queryParam("param1","value1")
                .queryParam("param2","value2")
                .sync();
    

    Note

    .path(xxx) must be called before .queryParam(xxx,xxx).


  4. For the POST method, the sample code is as follows:

    Poseidon.config(PConfig.init().accessKey(accessKey).secretKey(secretKey).debug())
                .url("https://{apigw-address}/lily/0.0.1/getPublic")
                .method("POST")
                .header("Content-Type", "application/json")
                .header("Cookie", "global_id=IAM_S_S7Yd5WXssqEBCququgzeR9JLNBnWr99S")
                .requestBody(
                    "{\n" + "  \"op\": \"pl\",\n" + "  \"offset\": 0,\n" + "  \"limit\": 10\n" + "}")
                .sync();
    

    Note

    Request header is optional. Specifications such as the type of request content can be included in the header as needed.


Asynchronous Request


The sample code is as follows:

Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey))
        .url("https://{apigw-address}/{service-name}/{api-version}/{api_name}?{param1=value1&param2=value2}")
        .method("GET").async( new PoseidonListener() {
              @Override
              public void onFailure(String errorMessage) {
                // TODO
              }

              @Override
              public void onResponse(String body) {
                // TODO
              }
            });


Support for Request and Response


Request provides the built-in support for the Header, Query, RequestBody, and Path parameters.

Exception Handling


Capture the PoseidonException to view specific API exception issues. For API service errors, refer to the API documentation.


Common error messages and description returned from PoseidonException are as follows:

Code

Description

Message

Cause

400

Bad Request

Cannot process request body

Failed to get request body.

401

Unauthorized

Invalid authentication credentials

Failed to authenticate the identification.

403

Forbidden

Your IP address is not allowed

The IP address is not allowed to access.

413

Payload Too Large

Request size limit exceeded

The request size exceeded the limit.

429

Too Many Requests

API rate limit exceeded

The number of requests exceeded the API request limit.

500

Internal Server Error

An unexpected error occurred

Failed to search from cache.

503

Service unavailable

Service unavailable

The service is not allowed to access.

Invoking Samples


After the development environment is ready, refer to the parameter descriptions and invocation examples in the API documentation to invoke the API.

Sample 1 - Using Java core SDK (GET Method)


The following sample shows how to get the asset details by using the Java core SDK to invoke the Get Asset API (with API logging feature disabled):

import com.enosiot.apim.poseidon.config.PConfig;
import com.enosiot.apim.poseidon.core.Poseidon;

public class GetAsset {
    public static void main(String[] args) {

        String accessKey = "{access_key_of_the_application}";
        String secretKey = "{secret_key_of_the_application}";

        String response = Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey))
                .url("https://{apigw-address}/asset-service/v2.1/assets?action=get&orgId={org_id}&assetId={asset_id}")
                .method("GET")
                .sync();
        System.out.println(response);
        }
    }


The returned data sample is as follows:

{
  "msg": OK,
  "code": 0,
  "data": {
    "modelId": "model_id",
    "assetId": "asset_id",
    "timezone": "+08:00",
    "name": {
      "i18nValue": {},
      "defaultValue": "asset_name"
    },
    "attributes": {
      "system": "System"
    },
    "modelIdPath": null,
    "orgId": "yourOrgId",
    "desc": null,
    "tags": {}
  },
  "requestId": "9a5cfbac-b2f8-4a37-b38d-8bccdd77d073"
}

Sample 2 - Using Java core SDK (POST Method)


The following sample shows how to update the name, description, attributes, timezone, and tags of an asset by using the Java core SDK to invoke the Update Asset API (with API logging feature enabled):

import com.enosiot.apim.poseidon.config.PConfig;
import com.enosiot.apim.poseidon.core.Poseidon;

public class UpdateAsset {
    public static void main(String[] args) {

        String accessKey = "{access_key_of_the_application}";
        String secretKey = "{secret_key_of_the_application}";

        String data = "{\"asset\":{\"assetId\":\"{asset_id}\",\"name\":{\"defaultValue\":\"Device_Name\",\"i18nValue\":{\"en_US\":\"Device_Name\",\"zh_CN\":\"Chinese name\"}},\"description\":\"Device_Description\",\"attributes\":{\"Brand\":\"Brand_Name\"},\"timezone\":\"+07:00\",\"tags\":{\"year\":\"2019\",\"site\":\"Site_Name\"}}}";

        String response = Poseidon.config(PConfig.init().appKey(accessKey).appSecret(secretKey).debug())
                .url("https://{apigw-address}/asset-service/v2.1/assets?action=update&orgId={org_id}")
                .method("POST")
                .requestBody(data)
                .sync();
        System.out.println(response);
    }
}


The returned data sample is as follows:

2019-7-10 16:35:12 [Poseidon] url: https://{apigw-address}/asset-service/v2.1/assets?action=update&orgId={org_id}
2019-7-10 16:35:12 [Poseidon] method: POST
2019-7-10 16:35:12 [Poseidon] headers: {}
2019-7-10 16:35:12 [Poseidon] requestBody: {"asset":{"assetId":"{asset_id}","name":{"defaultValue":"Device_Name","i18nValue":{"en_US":"Device_Name","zh_CN":"Chinese name"}},"description":"Device_Description","attributes":{"Brand":"Brand_Name"},"timezone":"+07:00","tags":{"year":"2019","site":"Site_Name"}}}
2019-7-10 16:35:13 [Poseidon] responseBody: {"code":0,"msg":"OK","requestId":"9d6b9869-4ffd-4964-a8ff-d150a0d1a91f","data":null}