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

# Authentication

> Learn how to authenticate your API requests with RegPilot using API keys.

## Overview

RegPilot uses **API keys** to authenticate requests. Your API keys carry many privileges, so be sure to keep them secure and never share them publicly.

<Warning>
  **Security First**: Never expose your API keys in client-side code, GitHub repositories, or public forums. Always use environment variables and server-side code for API requests.
</Warning>

## API Key Types

RegPilot offers different types of API keys for different use cases:

<CardGroup cols={2}>
  <Card title="Gateway Keys" icon="key">
    **Purpose**: AI Gateway API requests (`/api/ai/*`)

    **Prefix**: `sk_`

    **Permissions**: Chat completions, AI model access, Governor validation
  </Card>

  <Card title="Project Keys" icon="shield">
    **Purpose**: Compliance management APIs

    **Prefix**: `pk_`

    **Permissions**: Violations, models registry, compliance data
  </Card>
</CardGroup>

## Creating API Keys

<Steps>
  <Step title="Navigate to AI Gateway">
    Go to your project dashboard and select **AI Gateway → Overview**
  </Step>

  <Step title="Click Manage Keys">
    Click the **"Manage Keys"** button to open the API keys panel
  </Step>

  <Step title="Create New Key">
    Click **"Create New Key"**, give it a descriptive name, and save it immediately

    <Warning>
      API keys are only shown once at creation. If you lose a key, you'll need to generate a new one.
    </Warning>
  </Step>

  <Step title="Copy and Store Securely">
    Copy the key to your password manager or environment variables

    ```bash theme={null}
    # Example: .env.local
    REGPILOT_API_KEY=sk_1a2b3c4d5e6f7g8h9i0j...
    ```
  </Step>
</Steps>

## Authentication Methods

### Method 1: X-API-Key Header (Recommended)

The preferred method for authenticating API requests:

```bash theme={null}
curl -X POST https://regpilot.dev/api/ai/chat \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "Hello"}]}'
```

<CodeGroup>
  ```typescript TypeScript theme={null}
  const response = await fetch('https://regpilot.dev/api/ai/chat', {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.REGPILOT_API_KEY!,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      messages: [{ role: 'user', content: 'Hello' }],
    }),
  });
  ```

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

  response = requests.post(
      'https://regpilot.dev/api/ai/chat',
      headers={
          'X-API-Key': os.environ['REGPILOT_API_KEY'],
          'Content-Type': 'application/json',
      },
      json={
          'messages': [{'role': 'user', 'content': 'Hello'}]
      }
  )
  ```
</CodeGroup>

### Method 2: Authorization Bearer Token

Alternative authentication using the Authorization header:

```bash theme={null}
curl -X POST https://regpilot.dev/api/ai/chat \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type": application/json" \
  -d '{"messages": [{"role": "user", "content": "Hello"}]}'
```

### Method 3: SDK Authentication

When using the official RegPilot SDK, authentication is handled automatically:

<CodeGroup>
  ```typescript TypeScript SDK theme={null}
  import { RegPilot } from '@regpilot/sdk';

  const client = new RegPilot({
    apiKey: process.env.REGPILOT_API_KEY,
  });

  // Authentication handled automatically
  const response = await client.chat.create({
    messages: [{ role: 'user', content: 'Hello' }],
  });
  ```

  ```python Python SDK theme={null}
  from regpilot import RegPilot

  client = RegPilot(api_key=os.environ["REGPILOT_API_KEY"])

  # Authentication handled automatically
  response = client.chat.create(
      messages=[{"role": "user", "content": "Hello"}]
  )
  ```
</CodeGroup>

## Environment-Specific Keys

Use different API keys for different environments:

<Tabs>
  <Tab title="Development">
    ```bash .env.development theme={null}
    REGPILOT_API_KEY=sk_dev_1a2b3c4d...
    REGPILOT_ENVIRONMENT=development
    ```

    Development keys have:

    * Lower rate limits
    * Verbose logging enabled
    * Test mode activated
  </Tab>

  <Tab title="Staging">
    ```bash .env.staging theme={null}
    REGPILOT_API_KEY=sk_stg_5e6f7g8h...
    REGPILOT_ENVIRONMENT=staging
    ```

    Staging keys have:

    * Production-like rate limits
    * Minimal logging
    * Full feature access
  </Tab>

  <Tab title="Production">
    ```bash .env.production theme={null}
    REGPILOT_API_KEY=sk_prod_9i0j1k2l...
    REGPILOT_ENVIRONMENT=production
    ```

    Production keys have:

    * Full rate limits
    * Error-only logging
    * All features enabled
  </Tab>
</Tabs>

## Security Best Practices

<AccordionGroup>
  <Accordion title="Use Environment Variables" icon="shield">
    Never hardcode API keys in your source code:

    ```typescript theme={null}
    // ❌ Bad - Hardcoded API key
    const apiKey = 'sk_1a2b3c4d5e6f7g8h';

    // ✅ Good - Environment variable
    const apiKey = process.env.REGPILOT_API_KEY;
    ```
  </Accordion>

  <Accordion title="Server-Side Only" icon="server">
    Only use API keys in server-side code, never in client-side JavaScript:

    ```typescript theme={null}
    // ❌ Bad - Client-side API call
    // components/Chat.tsx
    const response = await fetch('/api/ai/chat', {
      headers: { 'X-API-Key': apiKey }
    });

    // ✅ Good - Server-side API route
    // app/api/chat/route.ts
    export async function POST(req: Request) {
      const response = await fetch('https://regpilot.dev/api/ai/chat', {
        headers: { 'X-API-Key': process.env.REGPILOT_API_KEY! }
      });
    }
    ```
  </Accordion>

  <Accordion title="Rotate Keys Regularly" icon="rotate">
    Rotate your API keys periodically:

    1. Create a new API key
    2. Update your environment variables
    3. Deploy the changes
    4. Delete the old key after verification
  </Accordion>

  <Accordion title="Use Least Privilege" icon="lock">
    Create separate API keys for different services:

    * **Frontend API route**: Gateway key for chat
    * **Backend service**: Project key for compliance data
    * **CI/CD pipeline**: Read-only key for testing
  </Accordion>

  <Accordion title="Monitor Usage" icon="chart-line">
    Regularly review API key usage in your dashboard:

    * Check for unusual activity
    * Monitor request patterns
    * Review error rates
    * Verify geographic locations
  </Accordion>
</AccordionGroup>

## Managing API Keys

### Viewing API Keys

View all your API keys in **AI Gateway → Overview → Manage Keys**:

* **Name**: Descriptive key name
* **Key Prefix**: First/last characters for identification
* **Created**: When the key was created
* **Last Used**: Most recent usage timestamp
* **Status**: Active or inactive

### Deactivating Keys

Temporarily disable a key without deleting it:

1. Go to **AI Gateway → Overview → Manage Keys**
2. Find the key you want to deactivate
3. Click the **"Deactivate"** button
4. Confirm the action

<Note>
  Deactivated keys will return `401 Unauthorized` errors until reactivated.
</Note>

### Deleting Keys

Permanently remove an API key:

1. Go to **AI Gateway → Overview → Manage Keys**
2. Find the key you want to delete
3. Click the **"Delete"** button
4. Confirm the action

<Warning>
  Deleted keys cannot be recovered. Make sure you've updated all services using the key before deleting it.
</Warning>

## Testing Authentication

Verify your API key is working correctly:

<CodeGroup>
  ```bash cURL theme={null}
  # Test authentication
  curl https://regpilot.dev/api/health \
    -H "X-API-Key: YOUR_API_KEY"

  # Expected response
  {
    "status": "ok",
    "authenticated": true,
    "project_id": "your-project-id"
  }
  ```

  ```typescript TypeScript theme={null}
  // test-auth.ts
  async function testAuth() {
    const response = await fetch('https://regpilot.dev/api/health', {
      headers: {
        'X-API-Key': process.env.REGPILOT_API_KEY!,
      },
    });
    
    const data = await response.json();
    
    if (data.authenticated) {
      console.log('✅ Authentication successful');
      console.log('Project ID:', data.project_id);
    } else {
      console.error('❌ Authentication failed');
    }
  }

  testAuth();
  ```

  ```python Python theme={null}
  # test_auth.py
  import requests
  import os

  response = requests.get(
      'https://regpilot.dev/api/health',
      headers={'X-API-Key': os.environ['REGPILOT_API_KEY']}
  )

  data = response.json()

  if data['authenticated']:
      print('✅ Authentication successful')
      print(f"Project ID: {data['project_id']}")
  else:
      print('❌ Authentication failed')
  ```
</CodeGroup>

## Error Responses

Common authentication errors and how to resolve them:

| Status Code | Error                                | Solution                                      |
| ----------- | ------------------------------------ | --------------------------------------------- |
| `401`       | `Missing API key`                    | Include `X-API-Key` header in your request    |
| `401`       | `Invalid or inactive API key`        | Check that your API key is correct and active |
| `403`       | `API key lacks required permissions` | Use a key with appropriate permissions        |
| `429`       | `Rate limit exceeded`                | Wait before retrying or upgrade your plan     |

## Rate Limits

API key rate limits depend on your plan:

<Tabs>
  <Tab title="Free Tier">
    * **Requests**: 1,000 per day
    * **Burst**: 10 requests per second
    * **Governor**: Not available
  </Tab>

  <Tab title="Pro Plan">
    * **Requests**: 100,000 per day
    * **Burst**: 100 requests per second
    * **Governor**: Available (\$300/month)
  </Tab>

  <Tab title="Enterprise">
    * **Requests**: Custom limits
    * **Burst**: Custom limits
    * **Governor**: Included
  </Tab>
</Tabs>

<Note>
  Rate limits are tracked per API key. Distribute load across multiple keys if needed.
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Make Your First Request" icon="rocket" href="/quickstart">
    Test your authentication setup
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Explore available endpoints
  </Card>

  <Card title="Security Best Practices" icon="shield" href="/guides/security-best-practices">
    Learn advanced security patterns
  </Card>

  <Card title="SDK Documentation" icon="code" href="/installation#sdk-integration">
    Use official SDKs
  </Card>
</CardGroup>
