Skip to content

OpenAPI SDK


OpenAPI SDK is used to call Guance Open API in different programming languages. The SDK encapsulates interfaces by module and handles URL concatenation, DF-API-KEY authentication, request parameter encoding, common response structures, and SDK errors.

The current SDK list provides GitHub repository links. You can choose the corresponding SDK based on your development language.

Development Language SDK Description
Python Python SDK Python SDK for Guance OpenAPI
JavaScript / TypeScript JavaScript / TypeScript SDK Node.js 18+ / TypeScript SDK
Java Java SDK Java SDK for Guance OpenAPI
PHP PHP SDK PHP 8.1+ SDK

Quick Start

After preparing according to the following steps, you can use the SDK to call Open API.

1 Confirm Permissions

Creating and managing API Keys requires Administrator or Owner permissions for the workspace. It is recommended to assign roles to API Keys based on the principle of least privilege, avoiding permissions that exceed actual needs.

2 Create an API Key

  1. Enter the Guance workspace.
  2. Click Management > API Key Management in the left navigation bar.
  3. Click Create Key in the upper right corner.
  4. Configure the name, role, and remarks.
  5. After successful creation, go to the API Key details page and copy the Key (Secret).

For detailed instructions, see API Keys Management.

3 Select Open API Endpoint

The Open API Endpoint needs to be passed during SDK initialization. Common SaaS Endpoints are as follows:

https://openapi.guance.com

For more site Endpoints, see Overview. For private deployment versions, use the actual deployed Endpoint.

4 Set Environment Variables

It is recommended to first write the Endpoint and API Key into environment variables, which can be reused directly in subsequent examples for various languages.

export DF_OPENAPI_ENDPOINT="https://openapi.guance.com"
export DF_API_KEY="Replace with your API Key"

5 Select Language and Prepare SDK

git clone https://github.com/GuanceCloud/guance-sdk-py.git
cd guance-sdk-py
python3 -m pip install -e .
git clone https://github.com/GuanceCloud/guance-sdk-js.git
cd guance-sdk-js
node --version

The SDK repository already contains the dist artifact. When integrating into a business project, you can use @guance/openapi-sdk as per the repository README.

git clone https://github.com/GuanceCloud/guance-sdk-java.git
cd guance-sdk-java
mvn test

To install into the local Maven repository, execute:

mvn install
git clone https://github.com/GuanceCloud/guance-sdk-php.git
cd guance-sdk-php
composer dump-autoload

6 Initialize Client

When initializing the Client, at least the Endpoint and API Key need to be passed.

import os
from guance_openapi_sdk import Client

client = Client(
    api_key=os.environ["DF_API_KEY"],
    base_url=os.environ["DF_OPENAPI_ENDPOINT"],
    timeout=30,
)
import { Client } from "@guance/openapi-sdk";

const client = new Client({
  apiKey: process.env.DF_API_KEY,
  baseUrl: process.env.DF_OPENAPI_ENDPOINT,
  timeoutMs: 30_000,
});
Client client = new Client(
    System.getenv("DF_OPENAPI_ENDPOINT"),
    System.getenv("DF_API_KEY")
);
<?php

use Guance\OpenAPI\Client;

$client = new Client(
    baseUrl: getenv('DF_OPENAPI_ENDPOINT'),
    apiKey: getenv('DF_API_KEY'),
    timeoutSeconds: 30,
);

First Call

It is recommended to choose a read-only interface for the first call, such as "Get Dashboard List". This interface corresponds to Dashboard List in the Open API documentation:

GET /api/v1/dashboards/list?pageIndex=1&pageSize=10

When calling with the SDK, only business parameters need to be passed; the DF-API-KEY will be automatically placed in the request header by the SDK.

response = client.board.list(query={"pageIndex": 1, "pageSize": 10})

print(response.content)
print(response.page_info)
print(response.trace_id)
const response = await client.board.list({
  query: { pageIndex: 1, pageSize: 10 },
});

console.log(response.content);
console.log(response.pageInfo);
console.log(response.traceId);
ApiResponseEnvelope response = client.board.list(
    RequestOptions.withQuery(Map.of("pageIndex", 1, "pageSize", 10))
);

System.out.println(response.contentJson);
System.out.println(response.pageInfo);
System.out.println(response.traceId);
$response = $client->board->list([
    'query' => ['pageIndex' => 1, 'pageSize' => 10],
]);

var_dump($response->content);
var_dump($response->pageInfo);
var_dump($response->traceId);

If the call is successful, success in the response will be true, code will be 200, and the business data will be located in content.

How to Fill Parameters

When reading each interface document, first look at the request method and path below the interface title, then look at the parameter location. Open API only uses GET and POST request methods: GET is used for data query and retrieval, POST is used for data changes such as creation, modification, and deletion.

Parameter Location in Interface Documentation SDK Parameter Example
Query Request Parameters query {"pageIndex": 1, "pageSize": 10}
Path Parameters path {"dashboard_uuid": "dsbd_xxxx32"}
Body Request Parameters body {"name": "demo workspace"}
Additional Request Headers headers {"X-Source": "internal-tool"}

Query Parameters

Query parameters are encoded into the URL query string. Taking Get Dashboard List as an example:

GET /api/v1/dashboards/list?pageIndex=1&pageSize=10
response = client.board.list(query={"pageIndex": 1, "pageSize": 10})
const response = await client.board.list({
  query: { pageIndex: 1, pageSize: 10 },
});
ApiResponseEnvelope response = client.board.list(
    RequestOptions.withQuery(Map.of("pageIndex", 1, "pageSize", 10))
);
$response = $client->board->list([
    'query' => ['pageIndex' => 1, 'pageSize' => 10],
]);

Path Parameters

Path parameters replace variables in the interface path. Taking Get Specified Dashboard as an example:

GET /api/v1/dashboards/{dashboard_uuid}/get
response = client.board.get(path={"dashboard_uuid": "dsbd_xxxx32"})
const response = await client.board.get({
  path: { dashboard_uuid: "dsbd_xxxx32" },
});
RequestOptions req = RequestOptions.create();
req.path.put("dashboard_uuid", "dsbd_xxxx32");
ApiResponseEnvelope response = client.board.get(req);
$response = $client->board->get([
    'path' => ['dashboard_uuid' => 'dsbd_xxxx32'],
]);

Body Parameters

Body parameters are used for POST requests. Taking Modify Current Workspace as an example:

POST /api/v1/workspace/modify
response = client.workspace.modify(body={"name": "demo workspace"})
const response = await client.workspace.modify({
  body: { name: "demo workspace" },
});
RequestOptions req = RequestOptions.create();
req.bodyJson = "{\"name\":\"demo workspace\"}";
ApiResponseEnvelope response = client.workspace.modify(req);
$response = $client->workspace->modify([
    'body' => ['name' => 'demo workspace'],
]);

How to Interpret the Response

Open API uses a unified response structure. Common fields are as follows:

Field Description
code Returned status code, consistent with HTTP status codes, fixed at 200 when there is no error
content Business data, specific type determined by the interface
pageInfo Pagination information for list interfaces
errorCode Error status code, empty indicates no error
message Error description
success Whether the interface call was successful
traceId Request trace ID, used for troubleshooting

List interfaces typically return both content and pageInfo. For example, pageInfo.totalCount represents the total number of data items matching the criteria.

How to Handle Errors

The SDK wraps Open API errors into exception types corresponding to the language. When troubleshooting, first check the HTTP status code, errorCode, message, and traceId.

from guance_openapi_sdk import ApiError

try:
    response = client.board.list(query={"pageIndex": 1, "pageSize": 10})
except ApiError as error:
    print(error.status)
    print(error.error_code)
    print(error.trace_id)
    print(error.envelope)
import { ApiError } from "@guance/openapi-sdk";

try {
  const response = await client.board.list({
    query: { pageIndex: 1, pageSize: 10 },
  });
} catch (error) {
  if (error instanceof ApiError) {
    console.log(error.status, error.errorCode, error.traceId);
    console.log(error.envelope);
  }
}
try {
    ApiResponseEnvelope response = client.board.list(
        RequestOptions.withQuery(Map.of("pageIndex", 1, "pageSize", 10))
    );
} catch (ApiException error) {
    System.out.println(error.httpStatus);
    System.out.println(error.errorCode);
    System.out.println(error.traceId);
    System.out.println(error.envelope.rawBody);
}
use Guance\OpenAPI\ApiException;

try {
    $response = $client->board->list([
        'query' => ['pageIndex' => 1, 'pageSize' => 10],
    ]);
} catch (ApiException $error) {
    echo $error->httpStatus . PHP_EOL;
    echo $error->errorCode . PHP_EOL;
    echo $error->traceId . PHP_EOL;
}

Common errors and limitations:

Scenario Description
Invalid API Key Returns ft.InvalidAPIKey
API Key Level Rate Limit The same API Key can make up to 200 requests per minute. Triggering this limit returns ft.TriggerApiAkCurrentLimiting
Workspace Level Rate Limit The same workspace supports up to 1000 Open API calls per minute. Triggering this limit returns ft.TriggerApiWorkspaceCurrentLimiting

For more information, see Common Response Structure, Common Error Definitions, and Usage Limits.

Data Query Example

If you need to query Metrics, Logs, Events, and other data, you can use the DQL data query interface. For DQL syntax, see DQL Query. For interface details, see DQL Data Query.

The following example queries the cpu metric:

response = client.query_data.query_data_v1(body={
    "queries": [
        {
            "qtype": "dql",
            "query": {
                "q": "M::`cpu`:(avg(`usage_idle`))",
                "timeRange": [1708911106000, 1708912906999],
                "interval": 10,
                "maxPointCount": 720,
                "tz": "Asia/Shanghai",
            },
        }
    ],
    "fieldTagDescNeeded": False,
})

print(response.content)
const response = await client.queryData.queryDataV1({
  body: {
    queries: [
      {
        qtype: "dql",
        query: {
          q: "M::`cpu`:(avg(`usage_idle`))",
          timeRange: [1708911106000, 1708912906999],
          interval: 10,
          maxPointCount: 720,
          tz: "Asia/Shanghai",
        },
      },
    ],
    fieldTagDescNeeded: false,
  },
});

console.log(response.content);
RequestOptions req = RequestOptions.create();
req.bodyJson = """
{
  "queries": [
    {
      "qtype": "dql",
      "query": {
        "q": "M::`cpu`:(avg(`usage_idle`))",
        "timeRange": [1708911106000, 1708912906999],
        "interval": 10,
        "maxPointCount": 720,
        "tz": "Asia/Shanghai"
      }
    }
  ],
  "fieldTagDescNeeded": false
}
""";

QueryDataContent content = client.queryData.queryDataV1Content(req);
System.out.println(content.data);
$response = $client->queryData->queryDataV1([
    'body' => [
        'queries' => [[
            'qtype' => 'dql',
            'query' => [
                'q' => 'M::`cpu`:(avg(`usage_idle`))',
                'timeRange' => [1708911106000, 1708912906999],
                'interval' => 10,
                'maxPointCount' => 720,
                'tz' => 'Asia/Shanghai',
            ],
        ]],
        'fieldTagDescNeeded' => false,
    ],
]);

var_dump($response->content);
Note

When performing data queries via Open API, the default role is administrator, but data access rules may still apply.

Troubleshooting Checklist

If the first call fails, check in the following order:

  1. Is DF_OPENAPI_ENDPOINT the Open API address corresponding to the current site?
  2. Is DF_API_KEY filled with the Key (Secret) from the API Key details page, not the Key ID?
  3. Does the workspace to which the API Key belongs match the workspace you want to query or modify?
  4. Does the API Key role have the permissions required for the target interface?
  5. Are Query, Path, and Body parameters placed in the corresponding SDK parameters?
  6. For list interfaces, are reasonable pageIndex and pageSize set?
  7. Has the API Key or workspace level rate limit been triggered?
  8. Is the traceId in the error message recorded for subsequent troubleshooting?

Feedback

Is this page helpful? ×