# Authentication

Create an API key, exchange it for a token, and send the token with every request.

[Listing your numbers](/docs/call-api/numbers) and [placing calls](/docs/call-api) need a token, which you get from your API key:

```text
1. Create an API key at docs.vonyx.si/api-keys: a client ID and a client secret   (once)
2. Exchange the key for a token                                                    (about once a day)
3. Send the token with every request: Authorization: Bearer YOUR_TOKEN
```

The [call details API](/docs/call-api/call-details) does not use the token: it takes your `client_id` parameter.

## 1. Create an API key

Sign in at [docs.vonyx.si](https://docs.vonyx.si/api-keys) and open **API Keys**. Create a key. You get a client ID and a client secret.

- The client secret is shown only once. Store it safely. If you lose it, create a new key.
- Create the key while signed in to the account that owns your Vonyx numbers. A key created under another account cannot see your numbers or place calls from them.

<Callout type="warn" title="Keep the secret on your server">
  Keep the client secret and your tokens on your server. Never put them in a browser, a mobile app or any code your users can see.
</Callout>

The client ID of the key identifies the key, not your account. Your account's ID is the `id` in the token reply below, and the **Account ID** in the console's **Settings**.

## 2. Get a token

```http
POST https://api.rylo.club/b2b/createAuthToken
Content-Type: application/json
```

```bash
curl -X POST https://api.rylo.club/b2b/createAuthToken \
  -H 'Content-Type: application/json' \
  -d '{
    "clientId": "YOUR_CLIENT_ID",
    "clientSecret": "YOUR_CLIENT_SECRET"
  }'
```

<TypeTable
  type={{
    clientId: { type: 'string', description: 'The client ID of your API key.', required: true },
    clientSecret: { type: 'string', description: 'The client secret of your API key.', required: true },
  }}
/>

Reply (`200`):

```json
{
  "affectedRows": 1,
  "authToken": "YOUR_TOKEN",
  "id": "5b9d2a7e-1c4f-4e8a-9d3b-6f0e2c8a1b47",
  "expiresIn": 86400
}
```

| Field | Description |
| --- | --- |
| `authToken` | The token. Send it with every request (step 3). |
| `id` | Your client ID: the account the token belongs to. |
| `expiresIn` | How long the token is valid, in seconds. `86400` is 24 hours. |

| HTTP | Reply | Meaning | What to do |
| --- | --- | --- | --- |
| `400` | `{"message":"clientId and clientSecret are required"}` | A field is missing or empty. | Send both fields. |
| `401` | `{"message":"Invalid client credentials"}` | The client ID or the client secret is wrong, or the key was revoked. | Check the key, or create a new one. |
| `429` | `{"message":"Rate limit exceeded. Max 60 requests per minute", "code":"rate_limit_exceeded"}` | More than 60 token requests a minute from your IP address. | Reuse your token instead of getting a new one per request; wait a minute. |
| `502` | `{"message":"..."}` | A temporary problem on our side. | Try again after a few seconds. |

Use the same token for all your requests until it expires; you don't need a new token per request. Get a new token shortly before `expiresIn` runs out, or when a request is answered with `401` and `invalid or expired token`.

## 3. Send the token

Add this header to every request to `https://api.vocalstack.site/v1/numbers` and `https://api.vocalstack.site/v1/calls`:

```http
Authorization: Bearer YOUR_TOKEN
```

The word `Bearer`, one space, then the `authToken` from step 2. Always use `https://`.

## Example

Reuses the token until shortly before it expires. A `401` changed nothing, so it is retried once with a new token.

<Tabs items={['Python', 'Node.js']}>
<Tab value="Python">

```python
import time
import requests  # pip install requests

AUTH_URL = "https://api.rylo.club/b2b/createAuthToken"
API_URL = "https://api.vocalstack.site"
CLIENT_ID = "YOUR_CLIENT_ID"          # from https://docs.vonyx.si/api-keys
CLIENT_SECRET = "YOUR_CLIENT_SECRET"  # keep it on your server

_token, _expires_at = None, 0.0


def get_token(force=False):
    """A valid token; a new one is fetched shortly before the old one expires."""
    global _token, _expires_at
    if force or _token is None or time.time() > _expires_at - 300:
        r = requests.post(AUTH_URL, json={"clientId": CLIENT_ID, "clientSecret": CLIENT_SECRET}, timeout=15)
        r.raise_for_status()
        d = r.json()
        _token, _expires_at = d["authToken"], time.time() + d.get("expiresIn", 86400)
    return _token


def api(method, path, timeout, body=None):
    """Calls the Vonyx API with the token. A 401 changed nothing, so it is retried once with a new token."""
    for attempt in (1, 2):
        r = requests.request(method, API_URL + path, json=body, timeout=timeout,
                             headers={"Authorization": "Bearer " + get_token(force=attempt == 2)})
        if r.status_code != 401:
            break
    return r


# Your numbers
r = api("GET", "/v1/numbers", timeout=15)
print(r.status_code, r.json())
numbers = [n["did"] for n in r.json()["data"]["numbers"]] if r.status_code == 200 else []

# Place a call from your first number
if numbers:
    r = api("POST", "/v1/calls", timeout=35, body={
        "did": numbers[0],
        "phone_number": "9876543210",
        "websocket_url": "wss://agent.example.com/ws",
        "sample_rate": 8000,
        "webhook_url": "https://example.com/vonyx/call-status",
    })
    print(r.status_code, r.json())
```

</Tab>
<Tab value="Node.js">

Node.js 18 or later. Uses the built-in `fetch`; put the key in environment variables on your server.

```js
const AUTH_URL = "https://api.rylo.club/b2b/createAuthToken";
const API_URL = "https://api.vocalstack.site";
const CLIENT_ID = process.env.VONYX_CLIENT_ID;         // from https://docs.vonyx.si/api-keys
const CLIENT_SECRET = process.env.VONYX_CLIENT_SECRET; // keep it on your server

let token = null;
let expiresAt = 0;

// A valid token; a new one is fetched shortly before the old one expires.
async function getToken(force = false) {
  if (force || !token || Date.now() > expiresAt - 5 * 60 * 1000) {
    const res = await fetch(AUTH_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ clientId: CLIENT_ID, clientSecret: CLIENT_SECRET }),
    });
    const body = await res.json();
    if (!res.ok) throw new Error(`token request failed: HTTP ${res.status} ${body.message || ""}`);
    token = body.authToken;
    expiresAt = Date.now() + (body.expiresIn || 86400) * 1000;
  }
  return token;
}

// Calls the Vonyx API with the token. A 401 changed nothing, so it is retried once with a new token.
async function api(method, path, timeoutMs, body) {
  let res;
  for (const attempt of [1, 2]) {
    res = await fetch(API_URL + path, {
      method,
      headers: {
        Authorization: "Bearer " + (await getToken(attempt === 2)),
        ...(body ? { "Content-Type": "application/json" } : {}),
      },
      body: body ? JSON.stringify(body) : undefined,
      signal: AbortSignal.timeout(timeoutMs),
    });
    if (res.status !== 401) break;
  }
  return { status: res.status, body: await res.json() };
}

// Your numbers
const list = await api("GET", "/v1/numbers", 15000);
console.log(list.status, JSON.stringify(list.body));
const numbers = list.status === 200 ? list.body.data.numbers.map((n) => n.did) : [];

// Place a call from your first number
if (numbers.length > 0) {
  const call = await api("POST", "/v1/calls", 35000, {
    did: numbers[0],
    phone_number: "9876543210",
    websocket_url: "wss://agent.example.com/ws",
    sample_rate: 8000,
    webhook_url: "https://example.com/vonyx/call-status",
  });
  console.log(call.status, JSON.stringify(call.body));
}
```

Save it as `calls.mjs` and run `node calls.mjs`.

</Tab>
</Tabs>

## Revoking a key

Revoke a key at [docs.vonyx.si](https://docs.vonyx.si/api-keys) when you no longer need it, or if its secret may have been exposed. Revoking stops new tokens from that key. A token already issued from it stays valid until it expires, at most 24 hours later.
