
# Authentication

The ContactLevel API uses **API key authentication**. Every request must include your API key in the `X-Api-Key` header.

## Obtaining Your API Key

Your API key is issued when your organization is set up on ContactLevel. You can view and manage keys from the ContactLevel dashboard under **Settings → API Keys**.

Each key is scoped to a single organization and grants access to all endpoints for that organization's data.

## Making Authenticated Requests

Include the `X-Api-Key` header in every request:

```bash
curl -X GET https://a.contactlevel.com/api/audiences/aud_01HX8G3K \
  -H "X-Api-Key: your_api_key_here"
```

```python
import requests

response = requests.get(
    "https://a.contactlevel.com/api/audiences/aud_01HX8G3K",
    headers={"X-Api-Key": "your_api_key_here"}
)
```

```javascript
const response = await fetch(
  "https://a.contactlevel.com/api/audiences/aud_01HX8G3K",
  {
    headers: { "X-Api-Key": "your_api_key_here" },
  }
);
```

## How It Works

1. Your raw API key is sent in the `X-Api-Key` header.
2. The server hashes the key using SHA-256 and looks it up in the database.
3. If the key is valid and not expired, the request proceeds with your organization's context.
4. If the key is missing, invalid, or expired, the API returns **401 Unauthorized**.

## Security Best Practices

- **Keep your key secret.** Do not commit keys to version control or expose them in client-side code.
- **Use environment variables** to store keys in your application.
- **Rotate keys periodically.** If you suspect a key has been compromised, regenerate it immediately from the dashboard.
- **Use server-side calls only.** The API key should never be sent from a browser or mobile app. Make API calls from your backend.

## Error Responses

| Status | Response | Meaning |
|--------|----------|---------|
| 401 | `{"detail": "Invalid or missing API key"}` | The `X-Api-Key` header is missing, the key is invalid, or it has expired. |
| 402 | `{"detail": "Insufficient credits"}` | Your organization does not have enough credits to complete the request. |

## Credits

Every API request consumes **1 credit** from your organization's balance. You can check your remaining credits at any time:

```bash
curl -X GET https://a.contactlevel.com/api/organizations/credit-balance \
  -H "X-Api-Key: your_api_key_here"
```

Response:

```json
{
  "total": 9500,
  "subscription": 5000,
  "purchased": 4000,
  "bonus": 500
}
```

| Credit Type | Description |
|-------------|-------------|
| **Subscription** | Included with your plan. Roll over monthly. |
| **Purchased** | Bought separately. Never expire. |
| **Bonus** | Promotional credits. May have an expiration date. |

If your balance reaches zero, API calls will return **402 Payment Required** until credits are added.