# API Keys

API keys provide programmatic access to the Seclai REST API. Use them to trigger agent runs, manage knowledge bases, create sources, and integrate Seclai into your applications and CI/CD pipelines.

> **Prefer OAuth for interactive use.** If you're connecting an MCP client (Claude Desktop, Cursor, etc.) or building a user-facing integration, [OAuth authentication](https://seclai.com/docs/api-introduction#authentication) is recommended. OAuth provides automatic token refresh and doesn't require managing secrets. API keys are best suited for server-to-server integrations and CI/CD pipelines.

## Overview

Each API key:

- Authenticates requests to the Seclai API via the `X-API-Key` header
- Is scoped to a single account (personal or organization)
- Can be named for easy identification (e.g., "Production", "CI / staging")
- Tracks all API calls made with it, including endpoints, status codes, and timestamps
- Reports credit usage consumed through its requests

You can create multiple keys per account to separate concerns (e.g., production vs. development) and rotate them independently.

> **Account scoping:** Each API key is permanently bound to the account it was created in. To access a different organization, create a separate key in that organization's account. The `X-Account-Id` header (used with [OAuth](https://seclai.com/docs/api-introduction#authentication) for org switching) is not supported for API key authentication.

---

## Creating an API Key

1. Navigate to **API Keys** in the left sidebar
2. Click **Create API Key**
3. Enter a descriptive name (optional, e.g., "CI / staging", "Production backend", "Mobile app")
4. Click **Create**

After creation, a dialog displays your new key:

> **Important:** The API key is only shown once at the time of creation. Copy it immediately and store it in a secure location (e.g., a password manager or secrets vault). You will not be able to view the full key again.

The dialog provides:

- A read-only text field displaying the full key
- A **Copy** button to copy it to your clipboard
- A **Done** button to close the dialog

**Example key names and their use cases:**

| Key Name                         | Use Case                                       |
| -------------------------------- | ---------------------------------------------- |
| <code>Production</code>          | Live application backend                       |
| <code>CI / staging</code>        | Continuous integration and staging environment |
| <code>Local development</code>   | Developer machine testing                      |
| <code>Mobile app</code>          | Mobile application integration                 |
| <code>Partner integration</code> | Third-party partner access                     |
| <code>Monitoring</code>          | Automated health check scripts                 |

---

## API Key List

The API Keys page displays all your keys in a paginated table:

| Column        | Width | Description                                                     |
| ------------- | ----- | --------------------------------------------------------------- |
| **Name**      | 45%   | Clickable name (shows "Untitled" if no name was set)            |
| **Status**    | 10%   | "Live" (green) for active keys, "Archived" for deactivated keys |
| **Created**   | 20%   | Date and time the key was created                               |
| **Last used** | 20%   | Date and time of the most recent API call, or "—" if never used |
| **Actions**   | 5%    | Context menu with available actions                             |

### Pagination

The table supports configurable page sizes:

| Page Size    | Best For              |
| ------------ | --------------------- |
| 10           | Quick overview        |
| 25 (default) | Standard view         |
| 50           | Larger teams          |
| 100          | Full inventory review |

Click the page size selector at the bottom of the table to change it.

### Quick Links

Above the table, documentation links provide quick access to:

- **SDKs & CLI** — Official SDKs for Python, JavaScript, Go, C#, and the CLI tool
- **API documentation** — Complete REST API reference

---

## API Key Details

Click any API key name to open its detail page. The header shows:

- **Key icon** with the key name (or "(unnamed)" if no name was set)
- **Created date** — When the key was created
- **Archived date** — If the key has been archived, when it was deactivated

Two tabs provide detailed information:

### API Calls Tab

A chronological table of every API call made with this key:

| Column       | Description                                                              |
| ------------ | ------------------------------------------------------------------------ |
| **Method**   | HTTP method (GET, POST, PUT, DELETE, PATCH)                              |
| **Endpoint** | The API endpoint called (e.g., <code>/agents</code>, <code>/runs</code>) |
| **Status**   | HTTP status code (200, 400, 401, 404, 500, etc.)                         |
| **Error**    | Error message if the call failed, or "—" for successful calls            |
| **Started**  | Timestamp of when the call was made                                      |

Use this tab to:

- Debug integration issues by checking for failed calls
- Verify that your application is calling the correct endpoints
- Monitor API usage patterns
- Identify unauthorized access attempts

**Example call entries:**

| Method | Endpoint            | Status | Error                         | Started         |
| ------ | ------------------- | ------ | ----------------------------- | --------------- |
| POST   | /agents/abc123/runs | 200    | —                             | Jan 15, 2:30 PM |
| GET    | /knowledge-bases    | 200    | —                             | Jan 15, 2:29 PM |
| POST   | /agents/def456/runs | 400    | Missing required field: input | Jan 15, 2:15 PM |
| DELETE | /sources/ghi789     | 404    | Source not found              | Jan 15, 1:45 PM |

### Usage Tab

The Usage tab shows credit consumption for requests made through this specific API key.

Features:

- **Time Frame Selector** — Choose relative ranges (24h, 7d, 30d, etc.) or custom date ranges
- **Usage Bar Chart** — Visual breakdown of credit consumption over time
- **Granularity** — Automatically adjusts (day/week/month) based on the selected range

Use this tab to:

- Track API-driven credit consumption separately from UI usage
- Allocate costs across different integrations (each key shows its own usage)
- Spot unexpected spikes in API-driven credit usage

---

## Archiving Keys

Archiving deactivates an API key while preserving its call history and usage data.

**When to archive:**

- Rotating to a new key
- Decommissioning an integration
- Revoking access for a former team member's integration

**How to archive:**

1. Click the **⋯** (actions) menu on the key row
2. Select **Archive**

**Important notes:**

- Archived keys display an "Archived" badge and the deactivation date
- The archive option is only available for keys that have call history
- Archived keys cannot make API calls — any request using an archived key will be rejected
- Archive is a one-way action (the key cannot be reactivated)
- Call history and usage data are preserved for auditing

---

## Deleting Keys

Deletion permanently removes an API key and all associated data.

**When to delete:**

- Removing a key that was created by mistake
- Cleaning up test keys that were never used

**How to delete:**

1. Click the **⋯** (actions) menu on the key row
2. Select **Delete**

**Important notes:**

- Only keys with **no call history** can be deleted
- If a key has been used to make API calls, you must **archive** it instead
- Attempting to delete a key with call history returns: _"This API key has call history and cannot be deleted. Archive it instead."_
- Deletion is permanent and cannot be undone

---

## Security Best Practices

| Practice                                 | Why                                                                                                         |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| **One key per user**                     | Never share API keys between users — each user should create their own key                                  |
| **Name your keys descriptively**         | Makes it easy to identify and audit which key is used where                                                 |
| **Use separate keys per environment**    | Isolate production from staging/development                                                                 |
| **Store keys in secrets managers**       | Never hardcode keys in source code                                                                          |
| **Rotate keys periodically**             | Create a new key, update your services, then archive the old one                                            |
| **Monitor the API Calls tab**            | Regularly check for unexpected endpoints or error patterns                                                  |
| **Archive unused keys**                  | Reduce your attack surface by deactivating keys you no longer need                                          |
| **Never commit keys to version control** | Use environment variables or <code>.env</code> files (and add <code>.env</code> to <code>.gitignore</code>) |
| **Prefer OAuth for user access**         | Use [OAuth authentication](https://seclai.com/docs/api-introduction#authentication) for MCP clients and user-facing apps      |

**Example: Key rotation workflow**

```
1. Create a new API key (e.g., "Production v2")
2. Copy the key to your secrets manager
3. Deploy updated configuration to your services
4. Verify traffic is flowing through the new key
   (check "Last used" column)
5. Archive the old key ("Production v1")
```

---

## Using API Keys

Include your API key in every request via the `X-API-Key` header:

```bash
curl https://api.seclai.com/agents \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json"
```

### With SDKs

**Python:**

```python
from seclai import Seclai

client = Seclai(api_key="YOUR_API_KEY")
agents = client.agents.list()
```

**JavaScript:**

```javascript
import { Seclai } from "@seclai/sdk";

const client = new Seclai({ apiKey: "YOUR_API_KEY" });
const agents = await client.agents.list();
```

**Go:**

```go
import "github.com/seclai/seclai-go"

client := seclai.NewClient("YOUR_API_KEY")
agents, err := client.Agents.List(ctx)
```

**C#:**

```csharp
using Seclai;

var client = new SeclaiClient("YOUR_API_KEY");
var agents = await client.Agents.ListAsync();
```

For more SDK examples, see [API Examples](https://seclai.com/docs/api-examples).

---

## Examples

### CI/CD Integration

Use a dedicated API key to trigger agent runs from your CI/CD pipeline:

```yaml
# GitHub Actions example
name: Run Analysis Agent
on:
  push:
    branches: [main]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Seclai agent
        run: |
          curl -X POST https://api.seclai.com/agents/$AGENT_ID/runs \
            -H "X-API-Key: ${{ secrets.SECLAI_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d '{"input": "Analyze latest changes in main branch"}'
```

### Monitoring Script

Create a dedicated "Monitoring" key for automated health checks:

```python
import requests

API_KEY = "YOUR_MONITORING_KEY"
AGENT_ID = "your-agent-id"

# Check agent status
response = requests.get(
    f"https://api.seclai.com/agents/{AGENT_ID}",
    headers={"X-API-Key": API_KEY}
)

agent = response.json()
print(f"Agent: {agent['name']}, Status: {agent['status']}")
```

### Multi-Environment Setup

Create separate keys for each environment:

```bash
# .env.development
SECLAI_API_KEY=dev_key_here

# .env.staging
SECLAI_API_KEY=staging_key_here

# .env.production
SECLAI_API_KEY=production_key_here
```

Then in your application:

```python
import os
from seclai import Seclai

client = Seclai(api_key=os.environ["SECLAI_API_KEY"])
```

---

## Troubleshooting

| Issue                          | Cause                                   | Solution                                                                        |
| ------------------------------ | --------------------------------------- | ------------------------------------------------------------------------------- |
| <code>401 Unauthorized</code>  | Invalid or missing API key              | Verify the key is correct and included in the <code>X-API-Key</code> header     |
| <code>403 Forbidden</code>     | Key doesn't have access to the resource | Check that the key belongs to the account that owns the resource                |
| MCP "user-scoped key" error    | Legacy key without user association     | Create a new API key — new keys are always user-scoped and MCP-compatible       |
| Cannot delete key              | Key has call history                    | Archive the key instead of deleting                                             |
| Key not working after rotation | Old key is still configured             | Update all services to use the new key, then archive the old one                |
| "Untitled" key name            | No name was provided at creation        | Key names cannot be changed after creation — archive and create a new named key |

---

## Next Steps

- [API Introduction](https://seclai.com/docs/api-introduction) — Full API overview with authentication details
- [API Reference](https://seclai.com/docs/api) — Complete endpoint documentation
- [API Examples](https://seclai.com/docs/api-examples) — Common patterns and code samples
- [SDKs](https://seclai.com/docs/sdks) — Official client libraries for Python, JavaScript, Go, and C#
- [Credits & Usage](https://seclai.com/docs/credits-usage) — Understand credit consumption for API calls
