# Authentication and API keys

Send your API key with every request: in the `Authorization: Bearer <key>` header from server code. Browser WebSockets cannot set headers, so use the `api_key` query parameter there.

> Source: https://tokenearly.com/en/developers/authentication · Docs index: https://tokenearly.com/en/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json

## Examples

Each example calls `GET /v1/me`, which returns the key's readable topics, limits and IP allowlist; it is the quickest way to check that a key works.

**cURL**

```bash
curl "https://api.tokenearly.com/v1/me" \
  -H "Authorization: Bearer te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**Python**

```python
import os, requests

KEY = os.environ["TOKENEARLY_API_KEY"]          # te_live_...
resp = requests.get(
    "https://api.tokenearly.com/v1/me",
    headers={"Authorization": f"Bearer {KEY}"},
    timeout=10,
)
print(resp.status_code, resp.json())
```

**Node.js**

```javascript
// Node 18+ (built-in fetch)
async function main() {
  const resp = await fetch("https://api.tokenearly.com/v1/me", {
    headers: { Authorization: `Bearer ${process.env.TOKENEARLY_API_KEY}` },
  });
  console.log(resp.status, await resp.json());
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

**X-API-Key**

```bash
curl "https://api.tokenearly.com/v1/me" \
  -H "X-API-Key: te_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
```

**WebSocket**

```python
import asyncio, os
import websockets  # pip install websockets

async def main():
    async with websockets.connect(
        "wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*",
        additional_headers={"Authorization": f"Bearer {os.environ['TOKENEARLY_API_KEY']}"},
    ) as ws:
        print(await ws.recv())   # {"op": "welcome", ...}

asyncio.run(main())
```

**Browser**

```javascript
// Browsers cannot set headers on WebSocket: pass the key as a query parameter.
// Only do this in tools you control; never ship a real key in public front-end code.
const ws = new WebSocket("wss://api.tokenearly.com/v1/stream?topics=announcement.*,news.*&api_key=te_live_...");
ws.onmessage = (e) => console.log(JSON.parse(e.data));
```

A missing or invalid key returns 401:

**401 response**

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "This API key does not exist or has been revoked.",
    "docs": "https://tokenearly.com/en/developers/errors"
  }
}
```

## Three ways to send it

| Method | Example | Use for |
|---|---|---|
| Authorization | `Authorization: Bearer te_live_…` | Recommended; REST, WebSocket and MCP |
| X-API-Key | `X-API-Key: te_live_…` | Tools that cannot set Bearer |
| api_key | `wss://…/v1/stream?api_key=te_live_…` | Browser WebSockets only (browsers cannot set headers) |

## Create a key

1. Sign in and open [Dashboard → Developer API](https://tokenearly.com/dashboard?tab=developer-api).
2. Press Create API key and name it; optionally add an IP allowlist.
3. Copy the key from the dialog. It is shown only once; we store only its hash.

An account can hold 1 key(s) by default; to rotate a key, press Reset. The key reads every topic your plan includes; choose topics per request or connection with the `topics` parameter, and check the effective set any time with [GET /v1/me](https://tokenearly.com/en/developers/rest/me).

A key belongs to your account and is only a credential for it: the topics your regular keys can read and [My alerts](https://tokenearly.com/en/developers/my-alerts) (the switch, history and cursors) stay with the account when you rotate keys. Stream subscriptions are chosen by your client on every connection with `topics` and are not stored on the key, so reconnect with the same parameters. The IP allowlist is set per key: a reset keeps it, a newly created key needs it filled in again.

### Reset a key

When a key leaks, is lost or is due for rotation, press Reset on it in the dashboard (trial keys too). A new key is issued and the old one stops working immediately: REST and MCP return 401 `invalid_api_key`, and open streams on the old key get `op = "error"` and close with 4001; do not reconnect automatically, switch to the new key first. The key id, name, IP allowlist, limits and expiry stay the same; resetting a trial key neither uses one of your applications nor extends its validity.

### How long a key works

Regular keys never expire on their own; they work while your account has a membership that includes the Developer API. When it expires, every regular key is refused with 403 `plan_required` (4003 on streams); renew and the same key works again immediately. Check the end date in `access_expires_at` from [GET /v1/me](https://tokenearly.com/en/developers/rest/me) or in the dashboard. 7, 3 and 1 days before and once it has expired we email you, push to your notification channels, and send a [notice](https://tokenearly.com/en/developers/rest/notices) (`access_expiring` / `access_expired`) to your integration. Trial keys do not follow a membership: they expire at their own `expires_at` (the same as `access_expires_at`), after which requests get 401 `key_expired` (4001 on streams). They cannot be renewed: apply for a new trial key, or subscribe and create a regular key.

> Treat the key like a password: never ship it in front-end code or commit it to a repository. If it leaks, reset or revoke it in the dashboard; the old key stops working and its open streams are closed immediately.

## IP allowlist (optional)

Add your servers' egress IPs to the key in the dashboard and only those addresses can use it, so a leaked key is useless elsewhere. Leave it empty to allow any address. You can edit it at any time; open streams pick up the change within a minute.

| Entry | Meaning |
|---|---|
| `203.0.113.5` | One IPv4 address |
| `203.0.113.0/24` | A range (CIDR) |
| `2001:db8::1` | IPv6 address or range |

REST and MCP calls from outside the allowlist return 403 `ip_not_allowed`; WebSocket sends an `op = "error"` message and closes with code 4003.

**403 response**

```json
{
  "error": {
    "code": "ip_not_allowed",
    "message": "Requests from 198.51.100.7 are not in this key's IP allowlist.",
    "docs": "https://tokenearly.com/en/developers/errors"
  }
}
```

## Edge cases

| Case | Behaviour |
|---|---|
| Both `Authorization: Bearer` and `X-API-Key` sent | `Authorization` wins; `X-API-Key` is ignored |
| `Authorization` is not Bearer (e.g. Basic) | Ignored; `X-API-Key` / `api_key` are used instead |
| Precedence | `Authorization: Bearer` > `X-API-Key` > `api_key`. The `api_key` query parameter only works on WebSocket and is ignored by REST (401 `missing_api_key`); a wrong key in Bearer is not retried with `api_key` (4001) |
| Lowercase `bearer`, extra spaces around the key | Accepted |

## Trial key

Accounts without the Developer API can apply for a trial key in the dashboard to get their code working first.

| Item | Trial key |
|---|---|
| Who can apply | A registered account with a verified email (not a guest account) |
| Valid for | 12 hours, then it stops working |
| How often | 6 times per account every 30 days; one active at a time |
| Data | All topics, real time; 7 days of history |
| Rate and connections | Same as the regular defaults: 1 request every 3 seconds, 1 concurrent connection(s) |
| After expiry | REST returns 401 `key_expired`; open streams are closed with code 4001 |

> Trial keys are for development and testing only, not for production or commercial use. Subscribe and create a regular key to go live.
