> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# API Keys Management

> Create, list, and manage API keys programmatically

# API Keys Management

Manage API keys for your projects via the Developer API. API keys are scoped to individual projects and inherit the project's security settings.

## Endpoints

### List API Keys

Retrieve all API keys for the authenticated user.

```http theme={"system"}
GET /api/v1/api-keys
```

**Headers:**

```
X-API-Key: your_api_key
```

**Response (200 OK)**

```json theme={"system"}
[
  {
    "id": "key_abc123",
    "name": "Production API",
    "prefix": "pg_live_xxxxxxxx",
    "project_id": "proj_abc123",
    "is_active": true,
    "created_at": "2025-01-15T10:30:00Z",
    "last_used_at": "2025-02-01T14:22:00Z"
  },
  {
    "id": "key_def456",
    "name": "Staging API",
    "prefix": "pg_live_xxxxxxxx",
    "project_id": "proj_abc123",
    "is_active": true,
    "created_at": "2025-01-20T08:15:00Z",
    "last_used_at": null
  }
]
```

<Note>
  Full API key values are never returned in list responses. Use the [Reveal](#reveal-api-key) endpoint to retrieve the full key.
</Note>

### Create API Key

Create a new API key for the current user.

```http theme={"system"}
POST /api/v1/api-keys
```

**Request Body**

```json theme={"system"}
{
  "name": "Production API",
  "project_id": "proj_abc123"
}
```

| Parameter    | Type     | Required | Description                       |
| ------------ | -------- | -------- | --------------------------------- |
| `name`       | `string` | Yes      | Descriptive name for the key      |
| `project_id` | `string` | Yes      | Project to associate the key with |

**Response (201 Created)**

```json theme={"system"}
{
  "id": "key_abc123",
  "name": "Production API",
  "key": "pg_live_xxxxxxxx...",
  "project_id": "proj_abc123",
  "is_active": true,
  "created_at": "2025-01-15T10:30:00Z"
}
```

<Warning>
  The `key` field is only returned once during creation. Store it securely -- you won't be able to see it again.
</Warning>

**Key limits by plan:**

| Plan  | Max API Keys per Project |
| ----- | ------------------------ |
| Free  | 1                        |
| Pro   | 5                        |
| Scale | Unlimited                |

### Delete API Key

Permanently delete an API key. This immediately revokes access.

```http theme={"system"}
DELETE /api/v1/api-keys/{key_id}
```

| Parameter | Type     | In   | Description             |
| --------- | -------- | ---- | ----------------------- |
| `key_id`  | `string` | Path | ID of the key to delete |

**Response (200 OK)**

```json theme={"system"}
{
  "message": "API key deleted successfully"
}
```

### Toggle API Key Status

Enable or disable an API key without deleting it.

```http theme={"system"}
PUT /api/v1/api-keys/{key_id}/toggle
```

| Parameter | Type     | In   | Description             |
| --------- | -------- | ---- | ----------------------- |
| `key_id`  | `string` | Path | ID of the key to toggle |

**Response (200 OK)**

```json theme={"system"}
{
  "id": "key_abc123",
  "name": "Production API",
  "is_active": false,
  "message": "API key deactivated"
}
```

<Tip>
  Use toggle instead of delete when you want to temporarily disable a key (e.g., during incident response) without losing the key configuration.
</Tip>

### Reveal API Key

Retrieve the full API key value. Use this to copy a key you've previously created.

```http theme={"system"}
GET /api/v1/api-keys/{key_id}/reveal
```

| Parameter | Type     | In   | Description             |
| --------- | -------- | ---- | ----------------------- |
| `key_id`  | `string` | Path | ID of the key to reveal |

**Response (200 OK)**

```json theme={"system"}
{
  "id": "key_abc123",
  "key": "pg_live_xxxxxxxx..."
}
```

## Code Examples

<Tabs>
  <Tab title="Python">
    ```python theme={"system"}
    import requests
    import os

    api_key = os.environ.get("PROMPTGUARD_API_KEY")
    base_url = "https://api.promptguard.co/api/v1/api-keys"

    headers = {
        "X-API-Key": api_key,
        "Content-Type": "application/json"
    }

    # List all API keys
    response = requests.get(base_url, headers=headers)
    keys = response.json()
    for key in keys:
        print(f"{key['name']}: {key['prefix']}... (active: {key['is_active']})")

    # Create a new API key
    response = requests.post(base_url, headers=headers, json={
        "name": "Backend Service",
        "project_id": "proj_abc123"
    })
    new_key = response.json()
    print(f"New key: {new_key['key']}")  # Save this!

    # Toggle a key off
    requests.put(f"{base_url}/{new_key['id']}/toggle", headers=headers)

    # Delete a key
    requests.delete(f"{base_url}/{new_key['id']}", headers=headers)
    ```
  </Tab>

  <Tab title="Node.js">
    ```typescript theme={"system"}
    const apiKey = process.env.PROMPTGUARD_API_KEY;
    const baseUrl = 'https://api.promptguard.co/api/v1/api-keys';

    const headers = {
      'X-API-Key': apiKey,
      'Content-Type': 'application/json'
    };

    // List all API keys
    const keys = await fetch(baseUrl, { headers }).then(r => r.json());
    keys.forEach(key => {
      console.log(`${key.name}: ${key.prefix}... (active: ${key.is_active})`);
    });

    // Create a new API key
    const newKey = await fetch(baseUrl, {
      method: 'POST',
      headers,
      body: JSON.stringify({
        name: 'Backend Service',
        project_id: 'proj_abc123'
      })
    }).then(r => r.json());
    console.log(`New key: ${newKey.key}`); // Save this!

    // Toggle a key off
    await fetch(`${baseUrl}/${newKey.id}/toggle`, {
      method: 'PUT',
      headers
    });

    // Delete a key
    await fetch(`${baseUrl}/${newKey.id}`, {
      method: 'DELETE',
      headers
    });
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={"system"}
    # List all API keys
    curl https://api.promptguard.co/api/v1/api-keys \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"

    # Create a new API key
    curl -X POST https://api.promptguard.co/api/v1/api-keys \
      -H "X-API-Key: $PROMPTGUARD_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"name": "Backend Service", "project_id": "proj_abc123"}'

    # Toggle API key status
    curl -X PUT https://api.promptguard.co/api/v1/api-keys/{key_id}/toggle \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"

    # Reveal full API key
    curl https://api.promptguard.co/api/v1/api-keys/{key_id}/reveal \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"

    # Delete API key
    curl -X DELETE https://api.promptguard.co/api/v1/api-keys/{key_id} \
      -H "X-API-Key: $PROMPTGUARD_API_KEY"
    ```
  </Tab>
</Tabs>

## Error Responses

| Status | Code                | Description                            |
| ------ | ------------------- | -------------------------------------- |
| 400    | `key_limit_reached` | Maximum API keys for your plan reached |
| 401    | `unauthorized`      | Invalid or missing API key             |
| 404    | `not_found`         | API key ID not found                   |

## Best Practices

1. **Name keys descriptively** -- Use names like "Production Backend" or "Staging Cron Job" so you can identify them later
2. **One key per service** -- Don't share keys between applications
3. **Rotate every 90 days** -- Create new key → update apps → delete old key
4. **Use toggle for incidents** -- Disable a compromised key immediately without losing the configuration
5. **Monitor last\_used\_at** -- Delete keys that haven't been used in a while
