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

# Authentication

> Learn how to authenticate with the AgentGate API

# Authentication

AgentGate uses organization API keys to authenticate all API requests. This page explains how to create, use, and manage your API keys.

## Overview

* All API requests require authentication via API key
* Keys are scoped to an organization, not individual users
* Keys can have limited scopes for security
* Use the `Authorization` header with Bearer token format

## Organization API Keys

### Key Format

AgentGate API keys follow this format:

```
org_live_xxxxxxxxxxxxxxxxxxxxxxxx
```

* `org_` prefix identifies it as an organization key
* `live_` indicates a production key
* The remaining characters are a unique identifier

### Creating API Keys

<Steps>
  <Step title="Access API Key Settings">
    Log in to your [AgentGate Dashboard](https://agentgate.mynewapi.com) and navigate to **Settings** → **API Keys**.
  </Step>

  <Step title="Create New Key">
    Click **Create API Key** and provide a descriptive name (e.g., "Production Backend", "CI/CD Pipeline").
  </Step>

  <Step title="Select Scopes">
    Choose the permissions your key needs. Use the principle of least privilege—only grant scopes that are necessary.
  </Step>

  <Step title="Copy and Store">
    Copy your API key immediately. It won't be shown again. Store it securely in your environment variables or secrets manager.
  </Step>
</Steps>

## Key Scopes and Permissions

API keys can be scoped to limit their capabilities:

| Scope               | Description                      |
| ------------------- | -------------------------------- |
| `work-orders:write` | Create work orders               |
| `work-orders:read`  | Read work order details          |
| `runs:read`         | Read run status and results      |
| `runs:write`        | Cancel runs                      |
| `credits:read`      | Check credit balance             |
| `webhooks:read`     | List and view webhooks           |
| `webhooks:write`    | Create, update, delete webhooks  |
| `templates:read`    | List and view templates          |
| `templates:write`   | Create, update, delete templates |
| `*`                 | Full access (wildcard)           |

<Tip>
  For development and testing, wildcard scope (`*`) is convenient. For production, use specific scopes.
</Tip>

## Using API Keys

### Header Format

Include your API key in the `Authorization` header:

```
Authorization: Bearer org_live_xxxxxxxxxxxxxxxxxxxxxxxx
```

### Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl https://agentgate.mynewapi.com/v1/credits \
    -H "Authorization: Bearer org_live_xxxxxxxxxxxxxxxxxxxxxxxx"
  ```

  ```typescript TypeScript theme={null}
  // Using the SDK (recommended)
  import { AgentGate } from '@agentgate/sdk';

  const client = new AgentGate({
    apiKey: process.env.AGENTGATE_API_KEY
  });

  // Using fetch directly
  const response = await fetch('https://agentgate.mynewapi.com/v1/credits', {
    headers: {
      'Authorization': `Bearer ${process.env.AGENTGATE_API_KEY}`
    }
  });
  ```

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

  api_key = os.environ['AGENTGATE_API_KEY']

  response = requests.get(
      'https://agentgate.mynewapi.com/v1/credits',
      headers={'Authorization': f'Bearer {api_key}'}
  )
  ```
</CodeGroup>

## Security Best Practices

### Never Commit Keys to Source Control

<Warning>
  Never commit API keys to Git repositories, even private ones. Use environment variables or secrets managers instead.
</Warning>

```bash theme={null}
# Good: Use environment variables
export AGENTGATE_API_KEY=org_live_xxxxxxxxxxxxxxxxxxxxxxxx

# Bad: Hardcoded in code
const apiKey = "org_live_xxxxxxxxxxxxxxxxxxxxxxxx"; // DON'T DO THIS
```

### Use Environment Variables

Store keys in environment variables and access them in your code:

<CodeGroup>
  ```typescript Node.js theme={null}
  const apiKey = process.env.AGENTGATE_API_KEY;
  if (!apiKey) {
    throw new Error('AGENTGATE_API_KEY environment variable is required');
  }
  ```

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

  api_key = os.environ.get('AGENTGATE_API_KEY')
  if not api_key:
      raise ValueError('AGENTGATE_API_KEY environment variable is required')
  ```
</CodeGroup>

### Minimum Necessary Scopes

Create keys with only the scopes needed for their specific use case:

* **Backend service**: `work-orders:write`, `runs:read`, `webhooks:write`
* **Monitoring dashboard**: `runs:read`, `credits:read`
* **CI/CD integration**: `work-orders:write`, `runs:read`

### Rotate Keys Periodically

Rotate API keys regularly and immediately if you suspect compromise:

1. Create a new API key with the same scopes
2. Update your applications to use the new key
3. Verify applications work with the new key
4. Revoke the old key

## Key Rotation

### When to Rotate

* **Regularly**: Every 90 days as a best practice
* **Immediately**: If a key may have been exposed
* **On team changes**: When team members leave

### Zero-Downtime Rotation

<Steps>
  <Step title="Create New Key">
    Create a new API key with identical scopes to the existing key.
  </Step>

  <Step title="Update Applications">
    Deploy your applications with the new API key.
  </Step>

  <Step title="Verify">
    Confirm all applications work correctly with the new key.
  </Step>

  <Step title="Revoke Old Key">
    Delete the old API key from the dashboard.
  </Step>
</Steps>

## Troubleshooting

### Common Errors

<AccordionGroup>
  <Accordion title="401 Unauthorized - Invalid API Key">
    The API key is malformed or doesn't exist.

    **Solutions:**

    * Verify the key format (`org_live_...`)
    * Check for typos or truncation
    * Ensure the key hasn't been revoked
  </Accordion>

  <Accordion title="401 Unauthorized - Missing API Key">
    No API key was provided in the request.

    **Solutions:**

    * Ensure the `Authorization` header is present
    * Use the `Bearer` prefix
    * Check for header name typos
  </Accordion>

  <Accordion title="403 Forbidden - Insufficient Permissions">
    The API key doesn't have the required scope.

    **Solutions:**

    * Check the key's scopes in the dashboard
    * Create a new key with the required scopes
    * Review the endpoint's required scopes in the API reference
  </Accordion>
</AccordionGroup>

### Debugging Steps

1. **Verify the header format**: `Authorization: Bearer <key>`
2. **Check key validity**: Ensure the key exists in your dashboard
3. **Confirm scopes**: Match required scopes with your key's scopes
4. **Test with cURL**: Isolate issues by testing directly with cURL

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Make your first authenticated API call
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/overview">
    Explore all API endpoints
  </Card>
</CardGroup>
