# Open API Overview

## What Is This

The Open API lets you call Analytics Agent's data analysis capabilities through standard HTTP interfaces. You simply send a natural language question, and the system automatically handles data querying, metric calculation, knowledge retrieval, and visualization generation, returning structured analysis results.

In short: **it turns Analytics Agent's conversational capabilities into a programmable interface**.

## Use Cases

| Use Case | Description |
|----------|-------------|
| Embed in internal systems | Integrate data Q&A capabilities into your business systems. Users ask questions in natural language, and the backend calls the API asynchronously to retrieve and display analysis results. |
| Automated workflows | Connect the API to automated processes. Trigger data analysis on a schedule or by events, retrieve structured results, and let your system handle subsequent processing (e.g., generate reports, write to a database). |
| Custom application integration | Call the Agent's analysis capabilities from your own BI tools or data platforms to retrieve metric calculation results and SQL, which your application then renders and displays. |

## What You Get

After calling the API, you receive the same analysis process and results as asking a question on the Analytics Agent page, including:

- **Knowledge retrieval results** — Business rules and definition entries returned by the Agent after consulting the knowledge base
- **Metric calculation results** — Semantic layer DSL (metricDsl) and physical layer DSL (physicalMetricDsl)
- **SQL statements** — Query SQL generated by the Agent (which you can execute in your system to retrieve data)
- **Chart metadata** — Chart type, column definitions, and corresponding SQL (your application must execute the SQL and render the chart)
- **Analysis summary** — A text summary in Markdown format with data interpretation

> Note: The API returns analysis process data and structured results. Presentation-layer tasks such as chart rendering and report formatting must be completed by your application.

## 5-Minute Quick Start

For a complete end-to-end example, see → [Quick Start](open-api-quick-start)

The core flow is just 4 steps:

```text
① Get Token → ② Create Session → ③ Ask Question → ④ Poll for Results
```

Minimal code (Python):

```python
import requests, time

BASE = "https://api.clickzetta.com/clickzetta-campaign-data"  # Domestic SaaS environment
SECRET_KEY = "your_app_secret_key"

# ① Get Token
token = requests.get(f"{BASE}/open/api/v1/appSecretKey/generateAuthToken",
                     params={"appSecretKey": SECRET_KEY}).json()["data"]["token"]

# ② Create Session
session_id = requests.post(f"{BASE}/open/session/safe_new",
    params={"tenantId": 10, "userId": 1, "loginToken": token},
    json={"tenantId": 10, "userId": 1, "domainId": 106,
          "title": "API Test", "loginToken": token}
).json()["data"]

# ③ Ask Question
question_id = requests.post(f"{BASE}/open/text2insight/query",
    params={"tenantId": 10, "userId": 1, "loginToken": token},
    json={"tenantId": 10, "userId": 1, "domainId": 106,
          "sessionId": session_id, "msg": "Sales trend by region for the past 6 months", "loginToken": token}
).json()["data"]["questionId"]

# ④ Poll for Results
while True:
    result = requests.post(f"{BASE}/open/safe_question_poll",
        params={"tenantId": 10, "userId": 1, "loginToken": token},
        json={"tenantId": 10, "userId": 1, "domainId": 106,
              "questionId": question_id, "loginToken": token}
    ).json()
    responses = result["data"]["responses"]
    last_type = responses[-1].get("dataType", "")
    if last_type in ("finish", "finish_stop", "error"):
        break
    time.sleep(2)

# Print final results
for r in responses:
    print(f"[{r.get('dataType')}] {r.get('message', '')[:80]}")
```

## API Interface List

| Interface | Description | Required |
|-----------|-------------|----------|
| [GenerateAuthToken](open-api-generate-auth-token) | Obtain authentication Token | Yes |
| [CreateSession](open-api-create-session) | Create a conversation session | No (can reuse an existing sessionId) |
| [Text2InsightQuery](open-api-text2insight-query) | Submit a data analysis request | Yes |
| [SafeQuestionPoll](open-api-safe-question-poll) | Poll for question results | Yes |
| [Text2InsightStop](open-api-text2insight-stop) | Stop a running analysis task | No |

## More Guides

- [Quick Start](open-api-quick-start) — Complete end-to-end code examples (curl + Python)
- [Understanding Response Results](open-api-response-guide) — Message type descriptions, display recommendations, and real output examples
