> ## 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.

# DialNexa API fundamentals

> Authenticate DialNexa API requests, paginate list responses, handle errors, and add production-safe retries.

DialNexa API fundamentals cover the four behaviors every production client needs: Bearer API key authentication, endpoint-specific pagination, structured error handling, and safe retry decisions. Use this page after the [Quickstart](https://dialnexa.com/docs/api-reference/quickstart.md) and before sending real customer traffic.

## Before you build a DialNexa API client

* Create an API key in **Settings > API Keys**.
* Use `https://api.dialnexa.com/v1` as the base URL.
* Keep API keys in server-side environment variables or a secrets manager.
* Read the individual endpoint page before relying on its request, response, side-effect, or retry behavior.

## Authenticate DialNexa API requests

An API key has a key ID and secret separated by a colon. Send the complete `key_id:secret` value as a Bearer token on every request.

```bash theme={null}
curl https://api.dialnexa.com/v1/voices \
  -H "Authorization: Bearer YOUR_API_KEY"
```

A missing, revoked, expired, or malformed key returns `401 Unauthorized`. On this endpoint the body is:

```json theme={null}
{
  "message": "API key is missing or invalid. You can generate this by logging in into dashboard"
}
```

Endpoints outside calls, batch calls, voices, languages, and LLMs return the full error envelope described in [Handle DialNexa API errors](#handle-dialnexa-api-errors), with a reason such as `Invalid API key` in `message`.

Every operation under **Endpoints** supports Bearer API key authentication. Never send an API key from browser or mobile client code, commit it to source control, or include it in logs and screenshots.

### Avoid common authentication mistakes

* Send the full `key_id:secret` value, not only the key ID.
* Use the `Authorization: Bearer ...` header, not `x-api-key`.
* Keep `/v1` in the configured base URL.
* Use separate keys for development, staging, and production.
* Rotate a key immediately after suspected exposure.

Webhook deliveries use a separate HMAC signature. For subscriptions created with the API, see [Verifying the signature](https://dialnexa.com/docs/api-reference/v1/webhooks/create.md#verifying-the-signature) for the `x-nexa-signature` raw-body check.

## Paginate DialNexa list responses

DialNexa list endpoints do not use one universal response envelope. Most paginated endpoints accept `page` and `limit`, but their record keys, metadata fields, defaults, and maximums vary. Treat each endpoint page as the source of truth.

```bash theme={null}
curl "https://api.dialnexa.com/v1/workflows?page=2&limit=50" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

| Endpoint | Records live in | Pagination fields |
| - | - | - |
| [`GET /v1/workflows`](https://dialnexa.com/docs/api-reference/v1/workflows/list) | `data.data` | `data.meta.totalItems`, `data.meta.itemsPerPage`, `data.meta.totalPages`, `data.meta.currentPage` |
| [`GET /v1/batch-calls`](https://dialnexa.com/docs/api-reference/v1/batches/list) | Root JSON array | Accepts `page` and `limit` (default `30`), but returns no pagination metadata in the API-key response |
| [`GET /v1/organization-phone-numbers`](https://dialnexa.com/docs/api-reference/v1/phone-numbers/list) | `data.items` | `data.meta.hasMore`, `data.meta.itemsPerPage`, `data.meta.currentPage`; default limit is `20` |
| [`GET /v1/voices`](https://dialnexa.com/docs/api-reference/v1/voices/list) | Root JSON array | Accepts `page` and `limit` (default `20`, maximum `50`), but returns no pagination metadata in the API-key response |
| [`GET /v1/user-webhooks`](https://dialnexa.com/docs/api-reference/v1/webhooks/list) | `data.webhooks` | `data.total`, `data.page`, `data.limit`, `data.totalPages`; default limit is `10` |
| [`GET /v1/agents`](https://dialnexa.com/docs/api-reference/v1/agents/list) | `data.agents` | None. The full list is returned. |
| [`GET /v1/voices/s2s`](https://dialnexa.com/docs/api-reference/v1/voices/s2s) | Root JSON array | None. The full list is returned. |
| [`GET /v1/workflows/{workflowId}/leads`](https://dialnexa.com/docs/api-reference/v1/workflow-leads/list) | `data.data` | `data.count` |
| [`GET /v1/calls`](https://dialnexa.com/docs/api-reference/v1/calls/list) | Root JSON array | Accepts `page` and `limit` (default `20`, maximum `200`), but returns no pagination metadata |
| [`GET /v1/knowledge-base`](https://dialnexa.com/docs/api-reference/v1/knowledge-base/list) | `data.items` | `data.meta.totalItems`, `data.meta.itemsPerPage`, `data.meta.totalPages`, `data.meta.currentPage` |
| [`GET /v1/languages`](https://dialnexa.com/docs/api-reference/v1/languages/list) | Root JSON array | None. The full catalog is returned. |
| [`GET /v1/llms`](https://dialnexa.com/docs/api-reference/v1/llms/list) and [`GET /v1/llms/fallback`](https://dialnexa.com/docs/api-reference/v1/llms/fallback) | Root JSON array | Accepts `page` and `limit` (default `20`, capped at `100`), but returns no pagination metadata |
| [`GET /v1/transcribers`](https://dialnexa.com/docs/api-reference/v1/transcribers/list) and [`GET /v1/transcribers/fallback`](https://dialnexa.com/docs/api-reference/v1/transcribers/fallback) | `data` | None. Each catalog is returned in full. |

Unfiltered resource endpoints use a success envelope containing `success`, `error`, `statusCode`, `message`, `data`, and `timestamp`. Some resources already have their own `data` property, so records can be under `data.data`. Calls, batches, voices, languages, and LLM catalogs have endpoint-specific response filtering. Do not use one universal unwrapping rule for every endpoint.

For an endpoint with `meta.totalPages`, continue until the current page reaches the reported total:

```typescript theme={null}
async function fetchAllWorkflows(apiKey: string) {
  const workflows = [];
  let page = 1;

  while (true) {
    const response = await fetch(
      `https://api.dialnexa.com/v1/workflows?page=${page}&limit=100`,
      { headers: { Authorization: `Bearer ${apiKey}` } }
    );
    if (!response.ok) throw new Error(`List workflows failed: ${response.status}`);

    const { data: { data, meta } } = await response.json();
    workflows.push(...data);
    if (page >= meta.totalPages) break;
    page += 1;
  }

  return workflows;
}
```

For calls, batch calls, voices, and LLM lists, stop when a page contains fewer records than the effective `limit` (voices allow at most `50`, LLM lists cap it at `100`). For phone numbers, continue while `data.meta.hasMore` is `true`. Languages and transcribers return their complete lists and should not be paged.

## Handle DialNexa API errors

Failed requests return one of two error bodies. Which one depends on the endpoint, the same way success responses do. Read the HTTP status from the response itself, not from the body.

**Calls, batch calls, voices, languages, and LLMs** return only `message`, plus `data` when the refusal has a code. A `400` message starts with `Request validation failed: `.

```json theme={null}
{
  "message": "Request validation failed: Agent agent_abc123 has 2 outbound numbers. Pass phone_number_id to choose which one to dial from.",
  "data": {
    "code": "PHONE_NUMBER_REQUIRED",
    "phone_number_ids": ["phn_abc123", "phn_def456"]
  }
}
```

**Every other endpoint** returns the full error envelope:

```json theme={null}
{
  "statusCode": 400,
  "error": true,
  "success": false,
  "data": [],
  "message": "url must be a URL address, events should not be empty",
  "errors": [
    "url must be a URL address",
    "events should not be empty"
  ]
}
```

| Field | Type | Meaning |
| - | - | - |
| `message` | string | Human-readable reason. Several validation messages are joined with `, `. Present on every error. |
| `data` | object or array | For a coded refusal, an object with `code` and the details listed for that code on the endpoint page. Otherwise an empty array in the full envelope, and absent on calls, batch calls, voices, languages, and LLMs. |
| `statusCode` | integer | Full envelope only. The HTTP status code. |
| `error`, `success` | boolean | Full envelope only. Always `true` and `false`. |
| `errors` | array of strings | Full envelope only. One entry per failed field for a request validation error; empty otherwise. |

Branch on `data.code` when it is present; the codes are stable, while message wording can change. On calls, batch calls, voices, languages, and LLMs, a `401` always carries the fixed message shown in [Authenticate DialNexa API requests](#authenticate-dialnexa-api-requests), and a `5xx` carries `An unexpected error occurred. Please try again later.`

### Common HTTP status codes

| Code | Meaning | What to do |
| - | - | - |
| `400 Bad Request` | The body or query failed validation. | Fix required fields, formats, enums, or unknown properties. |
| `401 Unauthorized` | The API key is missing, invalid, expired, or revoked. | Send the complete active key as a Bearer token, then confirm it with [Validate API Key](https://dialnexa.com/docs/api-reference/v1/auth/validate.md). |
| `402 Payment Required` | A call or batch was refused for billing: no spendable wallet balance (for a batch, also no billing plan), or the workspace's monthly spend cap is reached. | Top up the wallet, or wait for the cap to reset on the 1st (IST) or have it raised. Do not retry until then. |
| `403 Forbidden` | The action is not allowed for this resource or workspace. For calls and batches: the workspace owner's KYC is not verified for the destination, or Telephony settings block the destination. For calls, also when the number is on the workspace's DNC list; a batch or workflow upload skips listed numbers instead. Other endpoints return it for actions such as editing a published agent version. | Read `message`. For calls, complete KYC, enable the destination in **Workspace Settings > Telephony**, or call another number. |
| `404 Not Found` | The resource does not exist, belongs to another workspace, or the route is retired. | Confirm the resource ID and use a documented `/v1` endpoint. |
| `409 Conflict` | The operation conflicts with current resource state. | Read the resource and choose a valid next action. |
| `422 Unprocessable Entity` | An endpoint reports semantic validation failure. | Handle this only where the endpoint contract documents it. |
| `429 Too Many Requests` | The API key exceeded 150 requests in 60 seconds on this endpoint. | Wait for the number of seconds in `Retry-After`, then retry. |
| `500 Internal Server Error` | DialNexa encountered an unexpected failure. | Retry safe reads; verify writes before deciding whether to retry. |

Always check `response.ok` before using a response body:

```typescript theme={null}
async function dialNexaRequest(path: string, init: RequestInit = {}) {
  const response = await fetch(`https://api.dialnexa.com/v1${path}`, init);
  const text = await response.text();
  let body: any = null;
  try {
    body = text ? JSON.parse(text) : null;
  } catch {
    // A proxy or gateway can answer with a non-JSON page.
    body = { message: text };
  }

  if (!response.ok) {
    // data is an object with code for a coded refusal, otherwise [] or absent.
    const code = body?.data?.code;
    throw new Error(`DialNexa ${response.status}${code ? ` ${code}` : ""}: ${body?.message}`);
  }

  return body;
}
```

## Build reliable API clients

A timeout does not prove that a request failed. Repeating a write can create a duplicate resource, purchase another number, or place another call.

> [!WARNING]
>
> The current v1 contract does not define an idempotency header. Do not invent one.

### Rate limits

Requests are limited to **150 requests per 60 seconds per API key, counted separately for each endpoint**, so each operation has its own budget. Requests with a Bearer header are counted per API key (by key ID), so several of your servers sharing one key share each endpoint's budget; requests without a Bearer header are counted per IP address. Requests that fail authentication still count. The counters are kept in memory on each DialNexa API server instance, so the limit can apply per instance: do not assume one exact shared budget, and pace your client from the `X-RateLimit-*` headers and `429` responses you receive.

Responses within the limit carry `X-RateLimit-Limit`, `X-RateLimit-Remaining`, and `X-RateLimit-Reset` (seconds until the window resets). When the limit is exceeded the API returns `429 Too Many Requests` carrying only a `Retry-After` header with the number of seconds to wait; a `429` does not carry the `X-RateLimit-*` headers. The message is `Too many requests, please try again later.`

| Operation class | Examples | Automatic retry decision |
| - | - | - |
| Read only | List agents, get call, list voices | Safe after network errors, `429`, and transient `5xx` responses. |
| State transition | Publish agent, pause workflow, resume batch | Read the resource first and retry only if the transition did not happen. |
| Resource creation | Create agent, webhook, knowledge base, purchase phone number | Search or list by stable business data before creating again. |
| Billable external action | Create call, create batch call | Never retry blindly. Reconcile recent calls or batches first. |
| Destructive action | Delete agent, knowledge base, phone number, or webhook | Read first and treat a later `404` as a possible completed deletion. |

Set connection and total request timeouts that fit your application. For retry-safe requests, use capped exponential backoff with jitter and honor `Retry-After` when the response includes it.

```typescript theme={null}
async function getWithRetry(url: string, apiKey: string, attempts = 5) {
  for (let attempt = 0; attempt < attempts; attempt += 1) {
    const response = await fetch(url, {
      headers: { Authorization: `Bearer ${apiKey}` },
      signal: AbortSignal.timeout(15_000),
    });

    if (response.ok) return response.json();
    if (response.status !== 429 && response.status < 500) {
      throw new Error(`Non-retryable response: ${response.status}`);
    }

    const retryAfterHeader = response.headers.get("retry-after");
    const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : NaN;
    const delayMs = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000
      : Math.min(30_000, 500 * 2 ** attempt) + Math.random() * 250;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }

  throw new Error("Retry budget exhausted");
}
```

For calls, keep a local correlation record and save the returned DialNexa call ID, then reconcile with that ID. API-key call responses do not return arbitrary `metadata`. After an ambiguous timeout that returned no ID, list calls with `agent_id`, `start_date`, and `end_date` and compare each call's `to_number` before deciding whether another call is needed. These filters do not guarantee a unique match.

## Verify your API client

Before production traffic:

1. Confirm an authenticated list request returns `200`.
2. Test each list parser against the endpoint's actual response envelope.
3. Verify string and array error messages are both handled.
4. Confirm `4xx` failures are not retried automatically.
5. Simulate a transient read failure and confirm backoff is capped.
6. Simulate a timed-out write and confirm the client reads or reconciles before retrying.
7. Redact API keys, secrets, phone numbers, and sensitive metadata from logs.

## Troubleshoot API client behavior

| Problem | What to check |
| - | - |
| Every request returns `401` | Confirm the client sends the complete API key in `Authorization: Bearer YOUR_API_KEY`. |
| A list parser returns no records | Check whether records live in `data`, `items`, a resource-specific key, or the root array. |
| A former unversioned route returns `404` | Find the supported operation under **Endpoints** and rebuild the request against its documented `/v1` path and schema. |
| A write may have happened twice | Stop retries, list or read the affected resource, and reconcile with your stable business data. |
| Requests retry indefinitely | Set a maximum attempt count, cap the delay, and classify responses before retrying. |

## Related pages

* [Quickstart](https://dialnexa.com/docs/api-reference/quickstart.md): make and verify your first request.
* [TypeScript and Python examples](https://dialnexa.com/docs/api-reference/code-examples.md): copy complete integration workflows.
* [Webhooks](https://dialnexa.com/docs/api-reference/v1/webhooks/overview.md): verify signatures and process call-ended deliveries.
* [AI coding agent integration](https://dialnexa.com/docs/api-reference/ai-coding-agent-integration.md): generate a repository-specific implementation plan and code changes.


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