Skip to content

OpenAPI SDK


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

The current SDK list provides GitHub repository links. You can choose the SDK that matches your programming language.

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 completing the following steps, you can use the SDK to call the Open API.

1 Confirm Permissions

Creating and managing API Keys requires Administrator or Owner permissions in the workspace. It is recommended to assign the API Key a role based on the principle of least privilege, avoiding more permissions than actually needed.

2 Create an API Key

  1. Go to the Guance workspace.
  2. In the left navigation bar, click Manage > API Key Management.
  3. Click Create Key in the upper-right corner.
  4. Configure the name, role, and notes.
  5. After it is created, go to the API Key details page and copy the Key (secret).

For details, see API Key Management.

3 Select an Open API Endpoint

You need to pass the Open API Endpoint when initializing the SDK. Common SaaS Endpoints are shown below:

https://openapi.guance.com

For Endpoints of other sites, see Overview. For private deployments, use the Endpoint of your actual deployment.

4 Set Environment Variables

It is recommended to write the Endpoint and API Key into environment variables first, so that all the language examples below can reuse them directly.

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

5 Choose a Language and Prepare the 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 artifacts. When integrating it into a business project, use @guance/openapi-sdk as described in the repository README.

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

To install it to your local Maven repository, run:

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

6 Initialize the Client

To initialize the Client, you must pass at least the Endpoint and API Key.

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")
);

The PHP namespace must be consistent with the installed SDK package. The code identifiers in the use statement do not need to be translated.

<?php

use Guance\OpenAPI\Client;

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

First Call

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

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

When calling from the SDK, you only need to pass business parameters; the SDK automatically adds DF-API-KEY to the request header.

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 succeeds, success in the response is true, code is 200, and the business data is in content.

How to Fill In Parameters

When reading an API document, first check the request method and path below the interface title, and then check where the parameters are located. The Open API uses only two request methods, GET and POST: GET is for data query and retrieval, and POST is for data changes such as creating, modifying, and deleting.

Location in the API 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. Take 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 the variables in the interface path. Take Get the 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. Take Modify the 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'],
]);

Understanding the Response

The Open API uses a unified response structure. Common fields are listed below:

Field Description
code Returned status code, the same as the HTTP status code; it is always 200 when there is no error
content Business data; the specific type is determined by the interface
pageInfo Pagination information for list interfaces
errorCode Error status code; empty means no error
message Error description
success Whether the interface call succeeded
traceId Request trace ID, used for troubleshooting

List interfaces usually return both content and pageInfo. For example, pageInfo.totalCount indicates the total number of records that meet the conditions.

Error Handling

The SDK wraps Open API errors into the exception type of the corresponding 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 limiting A single API Key supports up to 200 requests per minute; once triggered, returns ft.TriggerApiAkCurrentLimiting
Workspace-level rate limiting A single workspace supports up to 1000 Open API calls per minute; once triggered, returns ft.TriggerApiWorkspaceCurrentLimiting

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

Query Data Example

To query data such as metrics, logs, and events, use the DQL data query interface. For DQL syntax, see DQL Query; for the interface, 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

Open API data queries default to the Administrator role and may still be subject to Data Access rules.

Troubleshooting Checklist

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

  1. Whether DF_OPENAPI_ENDPOINT is the Open API address corresponding to the current site;
  2. Whether DF_API_KEY is set to the Key (secret) on the API Key details page, not the Key ID;
  3. Whether the workspace that the API Key belongs to is the workspace you want to query or modify;
  4. Whether the API Key role has the permissions required by the target interface;
  5. Whether the Query, Path, and Body parameters are placed in the corresponding SDK parameters;
  6. Whether the list interface has reasonable pageIndex and pageSize set;
  7. Whether API Key-level or workspace-level rate limiting was triggered;
  8. Whether the traceId in the error message has been recorded for further troubleshooting.

Feedback

Is this page helpful?