> For the complete documentation index, see [llms.txt](https://docs.deltastream.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.deltastream.io/how-do-i.../call-deltastreams-rest-api.md).

# Call DeltaStream’s REST API

DeltaStream exposes a single **POST** endpoint for executing SQL statements:

```bash
POST https://<your-org-endpoint>/v2/statements
Content-Type: application/json
Authorization: Bearer <API_TOKEN>
Body: {"statement": "<DeltaStream SQL>"}
```

Some statements return **rows** (e.g., `SELECT`), others return only **acknowledgements** (e.g., `CREATE MATERIALIZED VIEW`). The response is JSON and easy to parse.

***

### 1) Create an API token

1. In the DeltaStream web UI, go to **Integration → API Tokens**.
2. Click **Create**, give the token a name, choose a **Role** (this controls permissions), and click **Create** again.
3. **Copy the token once** and store it securely (you won’t be able to view it again).

> Tip: Use the least-privileged role that still lets your statements succeed.

<figure><img src="/files/oAPsbUdyLqyv5ytY2ZpR" alt=""><figcaption></figcaption></figure>

***

### 2) Find your API endpoint

In the DeltaStream UI, click the **? (Help)** icon (bottom-left). Copy the **API ENDPOINT** for your org. See the screenshot below for details.

<figure><img src="/files/KOBORAQIpa17AzSOH1A0" alt=""><figcaption></figcaption></figure>

***

### 3) Make a request (recommended CURL patterns)

#### Use environment variables (safer)

```bash
export DS_ENDPOINT="https://api-<org-code>.deltastream.io/v2/statements"
export DS_TOKEN="<your-api-token>"

# Example: query a materialized view for a specific passenger
curl -s "$DS_ENDPOINT" \
  -H "Authorization: Bearer $DS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"statement":"SELECT * FROM flightdb.public.disrupted_premium_passengers WHERE passenger_id = '\''PASS-2451'\'';"}' | jq
```

**Why the funny quoting?**\
Inside a single-quoted bash string, use `'\''` to embed a single quote in SQL. If you don’t like that, use a heredoc:

```bash
read -r -d '' SQL <<'SQL'
SELECT *
FROM flightdb.public.disrupted_premium_passengers
WHERE passenger_id = 'PASS-2451';
SQL

curl -s "$DS_ENDPOINT" \
  -H "Authorization: Bearer $DS_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"statement\":\"$SQL\"}" | jq

```

**Windows PowerShell**

```bash
$DS_ENDPOINT = "https://api-<org-code>.deltastream.io/v2/statements"
$DS_TOKEN    = "<your-api-token>"
$SQL         = @"
SELECT *
FROM flightdb.public.disrupted_premium_passengers
WHERE passenger_id = 'PASS-2451';
"@

$Body = @{ statement = $SQL } | ConvertTo-Json -Compress
Invoke-RestMethod -Method Post -Uri $DS_ENDPOINT -Headers @{ Authorization = "Bearer $DS_TOKEN" } -ContentType "application/json" -Body $Body
```

***

### Sample JSON response (trimmed)

```json
{
  "createdOn": 1760293498,
  "data": [
    [
      "PASS-2451",
      "Mary Smith",
      "GOLD",
      "UA387",
      "DELAYED",
      "JFK",
      "ATL",
      "2025-10-12 02:41:12.828",
      "AISLE"
    ]
  ],
  "metadata": {
    "columns": [
      {"name":"passenger_id","nullable":false,"type":"VARCHAR"},
      {"name":"full_name","nullable":false,"type":"VARCHAR"},
      {"name":"loyalty_tier","nullable":false,"type":"VARCHAR"},
      {"name":"flight_id","nullable":false,"type":"VARCHAR"},
      {"name":"flight_status","nullable":false,"type":"VARCHAR"},
      {"name":"origin","nullable":false,"type":"VARCHAR"},
      {"name":"destination","nullable":false,"type":"VARCHAR"},
      {"name":"disruption_timestamp","nullable":false,"type":"TIMESTAMP"},
      {"name":"seating_preference","nullable":false,"type":"VARCHAR"}
    ],
    "context": {
      "databaseName":"Proactivecsa",
      "organizationID":"019718d7-1860-7f76-833d-1b0237282b6a",
      "roleName":"sysadmin",
      "schemaName":"public",
      "storeName":"KafkaCluster1"
    },
    "encoding":"json",
    "partitionInfo":[{"rowCount":1}]
  },
  "sqlState": "00000",
  "statementID": "0199d9ab-2d72-7841-8d02-c0ca23a27c04"
}
```

#### How to read this

* **data**: array of rows (each row is an array aligned to **metadata.columns**).
* **metadata.columns**: names, types, and nullability for each column in order.
* **sqlState**: SQL status code (`00000` indicates success).
* **statementID**: server-side identifier for auditing/debugging.
* **createdOn**: request processing timestamp (epoch seconds).

If your statement doesn’t return rows (e.g., `CREATE MATERIALIZED VIEW`, `INSERT`, `REFRESH`), **data** may be empty while `sqlState` still indicates success.

***

### Common pitfalls & fixes

* **401/403**: invalid/missing token or insufficient role permissions. Regenerate or change role.
* **400**: malformed JSON (check quoting) or invalid SQL.
* **Wrong endpoint**: ensure you’re hitting `.../v2/statements` on your org’s API domain.
* **Quoting issues**: prefer heredocs or use the environment-variable pattern above.

***

### Quick JS example (for agents/actions)

```javascript
async function runStatement(sql) {
  const res = await fetch("https://api-<org-code>.deltastream.io/v2/statements", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.DS_TOKEN}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ statement: sql })
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`DeltaStream ${res.status}: ${err}`);
  }
  const json = await res.json();
  // map rows to objects using metadata.columns
  const cols = json.metadata.columns.map(c => c.name);
  const rows = (json.data || []).map(r => Object.fromEntries(r.map((v,i) => [cols[i], v])));
  return { rows, meta: json.metadata, sqlState: json.sqlState, statementID: json.statementID };
}

```

***

### Security notes

* **Never hard-code tokens** in code or docs. Use env vars / secret managers.
* **Rotate** any token that was exposed publicly.
* Always use **HTTPS**.
* Scope tokens to the **minimal role** needed.

***

#### TL;DR

1. Create a token → 2) copy your org’s API endpoint → 3) `POST /v2/statements` with `{"statement":"<SQL>"}` and a Bearer token. That’s it.
