# API Keys

> Manage API keys for secure Sendable integration.

Source: https://wav1.recrav.com/docs/learn/api-keys

## API Key Basics [#api-key-basics]

Each API key:

* Is unique to a session
* Has full access to that session, unless you give it [permissions](#permissions)
* Can be revoked at any time
* Is only shown once at creation

## Permissions [#permissions]

A key can be limited to the parts of the API it needs. Permissions are a list of `resource:action` pairs. Keys created without permissions keep full access.

In the dashboard, pick **Permissions** when you create or edit a key (session keys under Session > API Keys, account keys under Settings > API Keys): Full access, Read only, Send only, Webhook manager, or Custom to choose actions per resource. The key list shows each key's permissions; hover a badge to see the exact scopes.

| Action  | Covers                                                                                                                                                                                                                                                                                                                               |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `read`  | `GET` routes, and `POST` routes that only look data up (`/v1/contacts/check`, `/v1/contacts/status`, `/v1/contacts/devices`, `/v1/contacts/disappearing-duration`, `/v1/message/history`, `/v1/presence/subscribe`, `/v1/newsletters/:id/subscribe-updates`)                                                                         |
| `write` | Other `POST`, `PUT`, `PATCH`, and `DELETE` routes                                                                                                                                                                                                                                                                                    |
| `admin` | Destructive or account-wide changes: session create, restart, end, logout, and delete; chat delete and clear; group and community participant changes; profile, privacy, default disappearing timer, and blocklist changes; newsletter delete, owner transfer, and admin demote; webhook create, update, delete, and secret rotation |

Actions do not include each other: a key with `message:write` can send but cannot list messages unless it also has `message:read`.

| Resource      | Routes                                                       |
| ------------- | ------------------------------------------------------------ |
| `session`     | `/v1/session/*`                                              |
| `message`     | `/v1/message/*`, `/v1/messages`                              |
| `media`       | `/v1/media`, `/v1/message/:messageId/media*`                 |
| `chats`       | `/v1/chats/*` (except labels), `/v1/chats.recent`            |
| `contacts`    | `/v1/contacts/*`                                             |
| `groups`      | `/v1/groups/*`                                               |
| `communities` | `/v1/communities/*`                                          |
| `account`     | `/v1/account/*`                                              |
| `labels`      | `/v1/labels/*`, `/v1/chats/:chatId/labels/*`, message labels |
| `business`    | `/v1/business/*`                                             |
| `status`      | `/v1/status/*`                                               |
| `newsletters` | `/v1/newsletters/*`                                          |
| `calls`       | `/v1/calls/*`                                                |
| `webhooks`    | `/webhooks/*`                                                |
| `events`      | `/v1/events`                                                 |
| `presence`    | `/v1/presence/*`                                             |

Common sets:

* **Read only**: `read` on every resource.
* **Send only**: `message:write`, `media:write`, `chats:read`, `contacts:read`. Good for bots and AI agents that only send.
* **Webhook manager**: `webhooks:read`, `webhooks:write`, `webhooks:admin`, `events:read`.

A request the key is not allowed to make gets `403` with the missing permission:

```json
{ "error": "insufficient_scope", "message": "api key is missing the chats:read permission", "required": "chats:read" }
```

## Creating an API Key [#creating-an-api-key]

### Step-by-Step [#step-by-step]

1. Select a session from dashboard
2. Go to "API Keys" tab
3. Click "Generate New Key"
4. Choose [permissions](#permissions) (Full access by default)
5. Copy the key immediately
6. Store it securely

⚠️ **Important**: The key is only shown once. If you lose it, you must create a new one.

## API Key Management [#api-key-management]

### View All Keys [#view-all-keys]

In the API Keys tab, see:

* Key ID (first 8 characters)
* Created date
* Last used
* Status (Active/Revoked)

### Revoke a Key [#revoke-a-key]

If a key is compromised:

1. Find the key in the list
2. Click "Revoke"
3. Confirm revocation
4. The key is immediately disabled

### Key Usage Statistics [#key-usage-statistics]

Monitor key usage:

* Requests per day
* Success rate
* Error rate
* Last used timestamp

## Security Best Practices [#security-best-practices]

### Store Keys Safely [#store-keys-safely]

❌ **Never do this:**

```javascript
// BAD: Hardcoded key
const apiKey = 'sk_live_abc123'
```

✅ **Do this instead:**

```javascript
// GOOD: Environment variable
const apiKey = process.env.SENDABLE_API_KEY
```

### Use .env Files [#use-env-files]

Create `.env`:

```bash
SENDABLE_API_KEY=sk_live_abc123
```

Add to `.gitignore`:

```
.env
.env.local
.env.production
```

### Rotate Keys Regularly [#rotate-keys-regularly]

Set a rotation schedule:

* Development: Monthly
* Production: Quarterly

Rotation process:

1. Generate new key
2. Update application config
3. Test with new key
4. Revoke old key
5. Monitor for errors

### Separate Environments [#separate-environments]

Use different keys for different environments:

| Environment | Key Prefix    | Session            |
| ----------- | ------------- | ------------------ |
| Development | `sk_dev_`     | Dev Session        |
| Staging     | `sk_staging_` | Staging Session    |
| Production  | `sk_live_`    | Production Session |

## Use Cases [#use-cases]

### Single Application [#single-application]

One app, one session, one key:

```
App → API Key → Sendable Session
```

### Multi-Tenant Application [#multi-tenant-application]

Different keys for different customers:

```
Customer A → API Key A → Session A
Customer B → API Key B → Session B
```

### Microservices [#microservices]

Each service gets its own key:

```
Notification Service → Key 1
Chat Service → Key 2
Marketing Service → Key 3
```

## Troubleshooting [#troubleshooting]

### "Invalid API Key" Error [#invalid-api-key-error]

1. Check key is copied correctly (no extra spaces)
2. Verify key hasn't been revoked
3. Confirm key belongs to correct session
4. Ensure `x-api-key` header is used

### Rate Limit Errors [#rate-limit-errors]

If you see `429 Too Many Requests`:

1. Check your current usage in dashboard
2. Implement retry with backoff
3. Consider upgrading your plan

### Key Not Working [#key-not-working]

1. Verify session is connected
2. Check session health status
3. Try regenerating the key
4. Contact support if persists

## API Key Limits [#api-key-limits]

| Plan       | Keys per Session | Rate Limit |
| ---------- | ---------------- | ---------- |
| Free       | 3                | 60/min     |
| Starter    | 10               | 300/min    |
| Pro        | Unlimited        | 1000/min   |
| Enterprise | Unlimited        | Custom     |

## Monitoring [#monitoring]

Track API key usage in dashboard:

* Total requests
* Failed requests
* Average response time
* Error breakdown

Set up alerts for:

* Unusual traffic spikes
* High error rates
* Key nearing rate limits
