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

# API Keys

> Create and manage API keys for your Gately integrations

API keys are used to authenticate your applications with Gately. There are two types of keys for different use cases.

<Info>
  **Testing the API?** Once you have an API key, you can test any endpoint directly in our docs using the interactive playground on each API page.
</Info>

## API Key Types

| Key Type       | Prefix       | Usage                    | Security                        |
| -------------- | ------------ | ------------------------ | ------------------------------- |
| **Public Key** | `gately_pk_` | Browser/client-side apps | Safe to expose in frontend code |
| **Secret Key** | `gately_sk_` | Server-side only         | Never expose publicly           |

<Warning>
  **Never expose secret keys (`gately_sk_`) in client-side code.** Use public keys for browser applications and secret keys only on the server.
</Warning>

## Creating API Keys

### Via Dashboard

1. Navigate to **Settings → API Keys** in your [Gately dashboard](https://app.usegately.com)
2. Click **Create API Key**
3. Choose the key type:
   * **Public Key** - For frontend/browser applications
   * **Secret Key** - For backend/server applications
4. Enter a descriptive name (e.g., "Production Frontend", "Backend API")
5. Click **Create**
6. Copy the key immediately - it won't be shown again

<Tip>
  After creating your API key, head to any API endpoint page (like [List Members](/docs/api-reference/members/list.mdx)) and use the playground to test it!
</Tip>

## API Key Format

### Public Key

```
gately_pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

### Secret Key

```
gately_sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

| Part        | Description                    |
| ----------- | ------------------------------ |
| `gately`    | Prefix identifying Gately keys |
| `pk` / `sk` | Public key / Secret key        |
| `live`      | Environment (live or test)     |
| `xxxx...`   | Unique key identifier          |

## Usage Examples

### Browser / Client-Side (Public Key)

```javascript theme={null}
import { GatelyClient } from '@gately/sdk'

// Safe to use in frontend code
const gately = new GatelyClient({
  apiKey: 'gately_pk_live_xxxxxxxx'
})

// Login user
await gately.login('user@example.com', 'password')
```

### React

```jsx theme={null}
import { GatelyProvider, useGately } from '@gately/sdk'

function App() {
  return (
    <GatelyProvider apiKey="gately_pk_live_xxxxxxxx">
      <YourApp />
    </GatelyProvider>
  )
}

function LoginButton() {
  const { login } = useGately()
  return <button onClick={() => login('user@example.com', 'pass')}>Login</button>
}
```

### CDN / Script Tag

```html theme={null}
<script 
  src="https://cdn.usegately.com/gately.min.js" 
  data-api-key="gately_pk_live_xxxxxxxx"
  defer
></script>
```

### Node.js / Server-Side (Secret Key)

```javascript theme={null}
import { GatelyNodeClient } from '@gately/sdk/node'

// Use secret key on server only
const gately = new GatelyNodeClient({
  apiKey: process.env.GATELY_SECRET_KEY // gately_sk_live_xxxxxxxx
})

// Server-side operations
const members = await gately.listMembers()
const member = await gately.createMember({
  email: 'user@example.com',
  full_name: 'John Doe'
})
```

### REST API (Secret Key)

```bash theme={null}
curl -X GET "https://api.usegately.com/api/v1/members" \
  -H "Authorization: Bearer gately_sk_live_xxxxxxxx"
```

### Python

```python theme={null}
import os
import requests

API_KEY = os.environ['GATELY_SECRET_KEY']

def get_members():
    response = requests.get(
        'https://api.usegately.com/api/v1/members',
        headers={
            'Authorization': f'Bearer {API_KEY}'
        }
    )
    return response.json()
```

## Permissions

Secret API keys can be scoped to specific permissions:

| Permission        | Description                    |
| ----------------- | ------------------------------ |
| `read:members`    | View member data               |
| `write:members`   | Create, update, delete members |
| `read:content`    | View protected content         |
| `write:content`   | Manage protected content       |
| `read:campaigns`  | View campaigns and stats       |
| `write:campaigns` | Create and send campaigns      |
| `read:contacts`   | View contacts and lists        |
| `write:contacts`  | Create and manage contacts     |
| `admin`           | Full access to all resources   |

Public keys have limited permissions by default (authentication and user profile access).

## Managing API Keys

### List All Keys

```bash theme={null}
curl -X GET "https://api.usegately.com/api/v1/api-keys" \
  -H "Authorization: Bearer YOUR_SECRET_KEY"
```

Response:

```json theme={null}
{
  "success": true,
  "data": [
    {
      "id": "key_123",
      "name": "Production Frontend",
      "type": "public",
      "prefix": "gately_pk_live_abc",
      "created_at": "2024-01-15T10:00:00Z",
      "last_used_at": "2024-01-20T15:30:00Z"
    },
    {
      "id": "key_456",
      "name": "Backend API",
      "type": "secret",
      "prefix": "gately_sk_live_xyz",
      "permissions": ["admin"],
      "created_at": "2024-01-15T10:00:00Z",
      "last_used_at": "2024-01-20T15:30:00Z"
    }
  ]
}
```

### Revoke a Key

```bash theme={null}
curl -X DELETE "https://api.usegately.com/api/v1/api-keys/key_123" \
  -H "Authorization: Bearer YOUR_SECRET_KEY"
```

## Environment Variables

Store your API keys in environment variables:

```bash theme={null}
# .env.local (for development)
NEXT_PUBLIC_GATELY_API_KEY=gately_pk_live_xxxxxxxx
GATELY_SECRET_KEY=gately_sk_live_xxxxxxxx
```

```javascript theme={null}
// Frontend (public key)
const gately = new GatelyClient({
  apiKey: process.env.NEXT_PUBLIC_GATELY_API_KEY
})

// Backend (secret key)
const gately = new GatelyNodeClient({
  apiKey: process.env.GATELY_SECRET_KEY
})
```

## Security Best Practices

<Steps>
  <Step title="Use the Right Key Type">
    Use public keys (`gately_pk_`) for frontend apps and secret keys (`gately_sk_`) for backend only.
  </Step>

  <Step title="Never Expose Secret Keys">
    Secret keys should never appear in frontend code, mobile apps, or public repositories.
  </Step>

  <Step title="Use Environment Variables">
    Store API keys in environment variables or a secrets manager, not in source code.
  </Step>

  <Step title="Rotate Regularly">
    Create new keys and revoke old ones periodically, especially after team member departures.
  </Step>

  <Step title="Use Minimal Permissions">
    Create secret keys with only the permissions needed for their specific use case.
  </Step>

  <Step title="Monitor Usage">
    Review API key usage in your dashboard to detect unauthorized access.
  </Step>
</Steps>

## Rate Limits

API keys are subject to rate limiting:

| Plan       | Requests/Minute |
| ---------- | --------------- |
| Free       | 60              |
| Pro        | 300             |
| Business   | 1000            |
| Enterprise | Custom          |

## Troubleshooting

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    * Verify the API key is correct and not revoked
    * Check that you're using the right key type for your environment
    * Ensure the Authorization header format is correct: `Bearer YOUR_KEY`
  </Accordion>

  <Accordion title="403 Forbidden">
    * The API key doesn't have permission for this action
    * Public keys have limited permissions - use a secret key for admin operations
    * Create a new key with the required permissions
  </Accordion>

  <Accordion title="429 Rate Limited">
    * You've exceeded the rate limit
    * Wait for the reset time or upgrade your plan
  </Accordion>

  <Accordion title="Invalid API Key Format">
    * Ensure your key starts with `gately_pk_` or `gately_sk_`
    * Check for extra spaces or characters when copying
  </Accordion>
</AccordionGroup>
