> ## Documentation Index
> Fetch the complete documentation index at: https://dialnexa.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript and Python examples

> Copy complete v1 workflows for agents, calls, call listing, and signed webhooks.

These examples use the HTTP API directly. Set `DIALNEXA_API_KEY` in your shell and never put the key in browser code, source control, logs, or screenshots.

## Goal: create, publish, and call an agent

### TypeScript

```typescript theme={null}
const apiKey = process.env.DIALNEXA_API_KEY!;
const baseUrl = "https://api.dialnexa.com/v1";

async function request(path: string, init: RequestInit = {}) {
  const response = await fetch(`${baseUrl}${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      ...init.headers,
    },
  });
  const text = await response.text();
  let body: any = null;
  try {
    body = text ? JSON.parse(text) : null;
  } catch {
    body = { message: text }; // a proxy or gateway can answer with a non-JSON page
  }
  if (!response.ok) throw new Error(`${response.status}: ${JSON.stringify(body)}`);
  return body;
}

const { data: agent } = await request("/agents", {
  method: "POST",
  body: JSON.stringify({
    title: "Appointment Assistant",
    language_id: "LANGUAGE_ID",
    voice_id: "VOICE_ID",
    prompt_text: "Confirm {{customer_name}}'s appointment.",
  }),
});

await request(`/agents/${agent.id}`, {
  method: "PATCH",
  body: JSON.stringify({ version_number: 0, is_published: true }), // a new agent's first draft is version 0
});

const call = await request("/calls", {
  method: "POST",
  body: JSON.stringify({
    agent_id: agent.id,
    phone_number: "+919876543210",
    metadata: { customer_name: "Priya" },
  }),
});
console.log(call.id);
```

### Python

```python theme={null}
import os
import requests

BASE_URL = "https://api.dialnexa.com/v1"
HEADERS = {
    "Authorization": f"Bearer {os.environ['DIALNEXA_API_KEY']}",
    "Content-Type": "application/json",
}

agent_response = requests.post(
    f"{BASE_URL}/agents",
    headers=HEADERS,
    json={
        "title": "Appointment Assistant",
        "language_id": "LANGUAGE_ID",
        "voice_id": "VOICE_ID",
        "prompt_text": "Confirm {{customer_name}}'s appointment.",
    },
    timeout=30,
)
agent_response.raise_for_status()
agent = agent_response.json()["data"]

publish_response = requests.patch(
    f"{BASE_URL}/agents/{agent['id']}",
    headers=HEADERS,
    json={"version_number": 0, "is_published": True},  # a new agent's first draft is version 0
    timeout=30,
)
publish_response.raise_for_status()

call_response = requests.post(
    f"{BASE_URL}/calls",
    headers=HEADERS,
    json={
        "agent_id": agent["id"],
        "phone_number": "+919876543210",
        "metadata": {"customer_name": "Priya"},
    },
    timeout=30,
)
call_response.raise_for_status()
print(call_response.json()["id"])
```

## Goal: list and reconcile calls

Use the saved call ID to reconcile records. Arbitrary request `metadata` is not returned in API-key call responses. If creation timed out before an ID was received, list calls with `agent_id`, `start_date`, and `end_date` and compare each call's `to_number` before repeating a billable request.

```typescript theme={null}
const response = await fetch("https://api.dialnexa.com/v1/calls?agent_id=AGENT_ID", {
  headers: { Authorization: `Bearer ${process.env.DIALNEXA_API_KEY}` },
});
if (!response.ok) throw new Error(`List calls failed: ${response.status}`);
const calls = await response.json();
const matching = calls.find((candidate: any) => candidate.id === call.id);
```

```python theme={null}
response = requests.get(
    f"{BASE_URL}/calls",
    headers=HEADERS,
    params={"agent_id": agent["id"]},
    timeout=30,
)
response.raise_for_status()
matching = next(
    (item for item in response.json() if item["id"] == call_response.json()["id"]),
    None,
)
```

## Goal: register and verify a webhook

```typescript theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

const secret = process.env.DIALNEXA_WEBHOOK_SECRET!;
const webhook = await request("/user-webhooks", {
  method: "POST",
  body: JSON.stringify({
    url: "https://example.com/webhooks/dialnexa",
    events: ["call.completed"],
    secret,
    is_active: true,
  }),
});

// The new subscription is in webhook.data.webhook; its id has the webhook_ prefix.
// x-nexa-signature is `sha256=<hex>`: HMAC-SHA256 of the raw body with your secret.
function verify(rawBody: Buffer, signatureHeader: string) {
  if (!signatureHeader || !signatureHeader.startsWith("sha256=")) return false;
  const expected = "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
  const supplied = Buffer.from(signatureHeader);
  const expectedBytes = Buffer.from(expected);
  return supplied.length === expectedBytes.length && timingSafeEqual(supplied, expectedBytes);
}
```

```python theme={null}
import hashlib
import hmac
import os

secret = os.environ["DIALNEXA_WEBHOOK_SECRET"]
webhook_response = requests.post(
    f"{BASE_URL}/user-webhooks",
    headers=HEADERS,
    json={
        "url": "https://example.com/webhooks/dialnexa",
        "events": ["call.completed"],
        "secret": secret,
        "is_active": True,
    },
    timeout=30,
)
webhook_response.raise_for_status()

# x-nexa-signature is `sha256=<hex>`: HMAC-SHA256 of the raw body with your secret.
def verify(raw_body: bytes, signature_header: str) -> bool:
    if not (signature_header or "").startswith("sha256="):
        return False
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_header)
```

## Verify before production

* Replace every placeholder with an ID returned by the catalog or create operation.
* Run the agent flow against a test destination you control.
* Confirm the call through [Get Call](https://dialnexa.com/docs/api-reference/v1/calls/get.md).
* Store webhook secrets in a secret manager and verify the raw body.
* Follow [API fundamentals](https://dialnexa.com/docs/api-reference/api-fundamentals.md#build-reliable-api-clients) before adding automatic retries.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.