# Examples

All credentials in these examples are read from environment variables (`OPENSTATX_TOKEN`). Never hand your workspace recovery key to an AI or put it in a script.

## curl: structured query

```bash
curl -sS -X POST https://openstatx.com/api/v1/query \
  -H "authorization: Bearer $OPENSTATX_TOKEN" -H 'content-type: application/json' \
  -d '{"site_ids":["'$SITE_ID'"],"dataset":"http_requests","metrics":["request_count"],"dimensions":["actor_class"],
       "time_range":{"start":"2026-09-29T00:00:00+09:30","end":"2026-09-30T00:00:00+09:30"},"timezone":"Australia/Adelaide"}'
```

## TypeScript

```ts
const res = await fetch("https://openstatx.com/api/v1/sites/" + process.env.SITE_ID + "/overview?preset=last_7_days", {
  headers: { authorization: "Bearer " + process.env.OPENSTATX_TOKEN },
});
const { data, meta } = await res.json();
console.log(data.totals.page_views, meta.quality_by_metric);
```

`packages/client` in the repository provides a typed client.

## Python

```python
import os, requests
r = requests.get(f"https://openstatx.com/api/v1/sites/{os.environ['SITE_ID']}/automation",
                 params={"preset": "last_7_days", "view": "clients"},
                 headers={"authorization": f"Bearer {os.environ['OPENSTATX_TOKEN']}"}, timeout=30)
r.raise_for_status()
for row in r.json()["data"]["rows"]:
    print(row)
```

## Server-side reporting (signed)

```ts
import { createHmac, createHash, randomBytes } from "node:crypto";
const body = JSON.stringify({ v: 1, site_id: process.env.SITE_ID, batch_id: crypto.randomUUID(), events: [
  { event_id: "order-1001", type: "conversion", ts: Date.now(), order_id: "1001", revenue_minor: 1200, currency: "AUD" },
]});
const ts = Math.floor(Date.now() / 1000), nonce = randomBytes(16).toString("hex");
const sig = createHmac("sha256", process.env.OPENSTATX_SIGNING_SECRET!).update(`${ts}.${nonce}.${createHash("sha256").update(body).digest("hex")}`).digest("hex");
await fetch("https://openstatx.com/api/v1/collect/server", { method: "POST", body, headers: {
  "content-type": "application/json", authorization: "Bearer " + process.env.OPENSTATX_INGEST_TOKEN,
  "x-openstatx-timestamp": String(ts), "x-openstatx-nonce": nonce, "x-openstatx-signature": "v1=" + sig } });
```

## Edge adapter (Cloudflare Worker)

```ts
import { wrapWithAnalytics } from "@openstatx/edge-adapter";
export default wrapWithAnalytics(originalHandler, { siteId: "st_...", endpoint: "https://openstatx.com", tokenEnv: "OPENSTATX_INGEST_TOKEN", secretEnv: "OPENSTATX_SIGNING_SECRET" });
```

The adapter does not change the original response's status code, headers, streaming or caching semantics; a failed report only records the loss and never affects your site.

## MCP client

```ts
import { Client } from "@modelcontextprotocol/client";
// See examples/ai/mcp-client.mjs in the repository: uses the Streamable HTTP transport with a Bearer credential and calls tools/list and get_report.
```
