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

# API Keys Service

> Manage API keys for service-to-service authentication

The API Keys service allows you to create and manage API keys for authenticating service accounts and external applications.

## Overview

```ts theme={null}
import { SnackBaseClient } from "@snackbase/sdk";

const client = new SnackBaseClient({
  baseUrl: "https://api.example.com",
});

// Access the API keys service
const apiKeys = client.apiKeys;
```

<Note>
  API keys are scoped to the current user and account. When you create a key,
  store it securely - the full key value is shown only once.
</Note>

## List API Keys

Get all API keys for the current user:

```ts theme={null}
const keys = await client.apiKeys.list();
```

Keys are masked for security, showing only the last 4 characters:

```ts theme={null}
[
  {
    "id": "key-id-1",
    "name": "Production App",
    "key": "sb_sk_...x9k2",  // Masked
    "is_active": true,
    "last_used": "2024-01-15T10:30:00Z",
    "created_at": "2024-01-01T00:00:00Z"
  }
]
```

## Get an API Key

Get details for a specific API key:

```ts theme={null}
const key = await client.apiKeys.get("key-id");
```

## Create an API Key

Create a new API key:

```ts theme={null}
const key = await client.apiKeys.create({
  name: "My Integration"
});
```

The response includes the full key value:

```ts theme={null}
{
  "id": "key-id-2",
  "name": "My Integration",
  "key": "sb_sk_a1b2c3d4e5f6g7h8i9j0",  // Full key - save this!
  "is_active": true,
  "created_at": "2024-01-15T10:30:00Z"
}
```

<Warning>
  Save the key value immediately after creation. The full key is shown only
  once and cannot be retrieved later.
</Warning>

## Revoke an API Key

Revoke (delete) an API key:

```ts theme={null}
await client.apiKeys.revoke("key-id");
```

<Warning>
  Revoking an API key is permanent. Any applications using this key will
  immediately lose access.
</Warning>

## Using API Keys

Initialize a client with an API key:

```ts theme={null}
const client = new SnackBaseClient({
  baseUrl: "https://api.example.com",
  apiKey: "sb_sk_a1b2c3d4e5f6g7h8i9j0"
});
```

The API key will be included in all requests via the `X-API-Key` header.

## Complete Example

API key management component:

```ts theme={null}
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@snackbase/sdk/react";

function ApiKeyManager() {
  const queryClient = useQueryClient();
  const { data: keys, isLoading } = useQuery({
    queryKey: ["api-keys"],
    queryFn: () => client.apiKeys.list()
  });

  const createMutation = useMutation({
    mutationFn: (data) => client.apiKeys.create(data),
    onSuccess: (key) => {
      // Show the key to the user to save
      alert(`Save this key - it won't be shown again:\n\n${key.key}`);
      queryClient.invalidateQueries(["api-keys"]);
    }
  });

  const revokeMutation = useMutation({
    mutationFn: (keyId) => client.apiKeys.revoke(keyId),
    onSuccess: () => {
      queryClient.invalidateQueries(["api-keys"]);
    }
  });

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h2>API Keys</h2>

      <button
        onClick={() => createMutation.mutate({ name: "New Key" })}
        disabled={createMutation.isPending}
      >
        Create New Key
      </button>

      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Status</th>
            <th>Last Used</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {keys?.map(key => (
            <tr key={key.id}>
              <td>{key.name}</td>
              <td>{key.is_active ? "Active" : "Inactive"}</td>
              <td>{key.last_used ? new Date(key.last_used).toLocaleString() : "Never"}</td>
              <td>
                <button
                  onClick={() => revokeMutation.mutate(key.id)}
                  disabled={revokeMutation.isPending}
                >
                  Revoke
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
```

## Best Practices

1. **Store keys securely**: Use environment variables or secret management systems
2. **Use descriptive names**: Name your keys to identify their purpose
3. **Rotate regularly**: Create new keys and revoke old ones periodically
4. **Monitor usage**: Check `last_used` to identify inactive keys
5. **Revoke unused keys**: Remove keys that are no longer needed

## Next Steps

* **[Auth API Keys](/sdk/js/auth/api-keys)** - Authenticate with API keys
* **[Users Service](/sdk/js/services/users)** - Manage user accounts
* **[Audit Logs](/sdk/js/services/audit-logs)** - Track API key usage
