# Open API Quick Start

> This guide helps you complete your first API call in 5 minutes, from asking a question to receiving analysis results.

## Prerequisites

Before you begin, prepare the following information:

| Item | Description | How to Obtain |
|------|-------------|---------------|
| API Base URL | Base URL for interface requests | See the section below |
| appSecretKey | Application secret key used to obtain an authentication Token | Generated by admin on the User Management page |
| tenantId | Tenant ID | View on the Settings configuration page |
| userId | User ID | View on the Settings configuration page |
| domainId | Analytics domain ID | Obtained from the URL on the analytics domain settings page |

### API Base URL

| Environment | Base URL |
|-------------|----------|
| Domestic SaaS | `https://api.clickzetta.com/clickzetta-campaign-data` |
| Overseas (Singapore) | `https://ap-southeast-1-alicloud.api.singdata.com/clickzetta-campaign-data` |
| Private Deployment (OP) | Contact your implementation team; each environment differs |

### Obtaining appSecretKey

Go to **Admin → User Management**, select the corresponding user, click Edit, and in the "App Secret Key" section click + **Generate Key**.

![](/.topwrite/assets/image_1780485364546.png =646)

### Obtaining tenantId and userId

Click the avatar in the bottom-left corner to go to the **Settings** configuration page:

![](/.topwrite/assets/image_1780485505876.png =226)

On the configuration page, you can see **Tenant ID** and **User ID**:

![](/.topwrite/assets/image_1780485442238.png =294)

### Obtaining domainId

Click the settings button (gear icon) on the analytics domain card:

![](/.topwrite/assets/image_1780485535438.png =298)

On the settings page, look at the browser address bar URL — the number at the end is the **domainId**:

![](/.topwrite/assets/image_1780485554164.png =481)

## Complete Flow (curl)

### Step 1: Get a Token

For detailed parameters, see → [GenerateAuthToken](open-api-generate-auth-token)

```bash
curl "https://api.clickzetta.com/clickzetta-campaign-data/open/api/v1/appSecretKey/generateAuthToken?appSecretKey=YOUR_SECRET_KEY"
```

Response:

```json
{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiJ9..."
  }
}
```

Save the `data.token` value — it is required for all subsequent requests.

### Step 2: Create a Session (Optional)

For detailed parameters, see → [CreateSession](open-api-create-session)

If you already have a sessionId, you can skip this step.

```bash
curl -X POST "https://api.clickzetta.com/clickzetta-campaign-data/open/session/safe_new?tenantId=YOUR_TENANT_ID&userId=YOUR_USER_ID&loginToken=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tenantId": YOUR_TENANT_ID,
    "userId": YOUR_USER_ID,
    "domainId": YOUR_DOMAIN_ID,
    "title": "My First API Call",
    "loginToken": "YOUR_TOKEN"
  }'
```

Response:

```json
{
  "success": true,
  "data": 4729
}
```

`data` is your `sessionId`.

### Step 3: Ask a Question

For detailed parameters, see → [Text2InsightQuery](open-api-text2insight-query)

```bash
curl -X POST "https://api.clickzetta.com/clickzetta-campaign-data/open/text2insight/query?tenantId=YOUR_TENANT_ID&userId=YOUR_USER_ID&loginToken=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tenantId": YOUR_TENANT_ID,
    "userId": YOUR_USER_ID,
    "domainId": YOUR_DOMAIN_ID,
    "sessionId": YOUR_SESSION_ID,
    "msg": "Show me the sales trend by region for the past 6 months",
    "loginToken": "YOUR_TOKEN"
  }'
```

Response:

```json
{
  "success": true,
  "data": {
    "questionId": 34339,
    "sessionId": 4729,
    "status": "running"
  }
}
```

Save the `data.questionId`.

### Step 4: Poll for Results

For detailed parameters, see → [SafeQuestionPoll](open-api-safe-question-poll)

Call every 2 seconds until the `dataType` of the last message is `finish`, `finish_stop`, or `error`.

```bash
curl -X POST "https://api.clickzetta.com/clickzetta-campaign-data/open/safe_question_poll?tenantId=YOUR_TENANT_ID&userId=YOUR_USER_ID&loginToken=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tenantId": YOUR_TENANT_ID,
    "userId": YOUR_USER_ID,
    "domainId": YOUR_DOMAIN_ID,
    "questionId": YOUR_QUESTION_ID,
    "loginToken": "YOUR_TOKEN"
  }'
```

When the analysis is complete, the response will contain the full `responses` array. For how to interpret these returned contents, see [Understanding Response Results](open-api-response-guide).

## Complete Flow (Python)

```python
import requests
import time
import json

# === Configuration ===
BASE_URL = "https://api.clickzetta.com/clickzetta-campaign-data"  # Domestic SaaS environment
APP_SECRET_KEY = "your_app_secret_key"
TENANT_ID = 10
USER_ID = 1
DOMAIN_ID = 106

# === Step 1: Get Token ===
resp = requests.get(
    f"{BASE_URL}/open/api/v1/appSecretKey/generateAuthToken",
    params={"appSecretKey": APP_SECRET_KEY}
)
token = resp.json()["data"]["token"]
print(f"Token obtained successfully")

# === Step 2: Create Session ===
resp = requests.post(
    f"{BASE_URL}/open/session/safe_new",
    params={"tenantId": TENANT_ID, "userId": USER_ID, "loginToken": token},
    json={"tenantId": TENANT_ID, "userId": USER_ID, "domainId": DOMAIN_ID,
          "title": "API Quick Start", "loginToken": token}
)
session_id = resp.json()["data"]
print(f"Session created successfully, sessionId = {session_id}")

# === Step 3: Ask Question ===
resp = requests.post(
    f"{BASE_URL}/open/text2insight/query",
    params={"tenantId": TENANT_ID, "userId": USER_ID, "loginToken": token},
    json={"tenantId": TENANT_ID, "userId": USER_ID, "domainId": DOMAIN_ID,
          "sessionId": session_id, "msg": "Show me the sales trend by region for the past 6 months", "loginToken": token}
)
question_id = resp.json()["data"]["questionId"]
print(f"Question submitted successfully, questionId = {question_id}")

# === Step 4: Poll for Results ===
print("Waiting for analysis to complete...")
poll_count = 0
max_polls = 180  # Poll at most 180 times (360 seconds)

while poll_count < max_polls:
    time.sleep(2)
    poll_count += 1

    resp = requests.post(
        f"{BASE_URL}/open/safe_question_poll",
        params={"tenantId": TENANT_ID, "userId": USER_ID, "loginToken": token},
        json={"tenantId": TENANT_ID, "userId": USER_ID, "domainId": DOMAIN_ID,
              "questionId": question_id, "loginToken": token}
    )
    data = resp.json()["data"]
    responses = data.get("responses", [])

    if not responses:
        continue

    last_type = responses[-1].get("dataType", "")
    if last_type in ("finish", "finish_stop", "error"):
        print(f"Analysis complete (polled {poll_count} times)")
        break

# === Display Results ===
print("\n" + "=" * 60)
print("Analysis Results:")
print("=" * 60)

for i, r in enumerate(responses):
    data_type = r.get("dataType", "unknown")

    if data_type == "summary":
        # Analysis summary
        summary = r.get("modelRes", {}).get("data", {}).get("summaryData") or r.get("message", "")
        print(f"\nAnalysis Summary:\n{summary}")

    elif data_type == "metric":
        # Metric calculation
        message = r.get("message", "")
        print(f"\nMetric: {message}")

    elif data_type == "echarts_plus":
        # Chart
        message = r.get("message", "")
        sql = r.get("modelRes", {}).get("data", {}).get("calculateSql", "")
        print(f"\nChart: {message}")
        if sql:
            print(f"   SQL: {sql[:100]}...")

    elif data_type == "error":
        print(f"\nError: {r.get('message', '')}")
```

## Sample Output

Running the Python script above produces output similar to this:

```text
Token obtained successfully
Session created successfully, sessionId = 4729
Question submitted successfully, questionId = 34339
Waiting for analysis to complete...
Analysis complete (polled 36 times)

============================================================
Analysis Results:
============================================================

Metric: Metric: Total sales by region for the past 6 months

Chart: Sales trend by region (2025.07-2026.01)
   SQL: SELECT region, month, SUM(sales) AS total_sales FROM ...

Analysis Summary:
**Sales Trend Analysis by Region:**
- East China region continues to lead, accounting for 42% of total sales
- South China region has the fastest growth, up 15% month-over-month
...
```

## Next Steps

* Understand the meaning of each message type in the response → [Understanding Response Results](open-api-response-guide)
* View the complete parameter definitions for each interface → [API Interface List](open-api-overview#api-interface-list)
* Specify a model: add the `modelSettings` parameter when asking a question → [Text2InsightQuery](open-api-text2insight-query)

^
