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

# Authentication

> Learn how to authenticate your API requests

## Overview

The Snippets AI API uses **Bearer token authentication**. All API requests must include a valid API key in the `Authorization` header.

## Getting Your API Key

<Steps>
  <Step title="Log into your workspace">Navigate to your Snippets AI app</Step>
  <Step title="Go to Admin">Click on **API Access**</Step>

  <Step title="Create a new API key">
    Click **New API Key** and configure: - **Key name**: A descriptive name for
    identification - **Team permissions**: Select which teams this key can
    access - **All teams**: Toggle if you want workspace-wide access
  </Step>

  <Step title="Copy your key">
    Copy the secret key immediately - you won't be able to see it again!
  </Step>
</Steps>

<Warning>
  **Keep your API key secure!** Never share it publicly or commit it to version
  control. Anyone with your API key can access your snippets and consume your
  API quota.
</Warning>

## Using Your API Key

Include your API key in the `Authorization` header of every request using the Bearer authentication scheme:

```
Authorization: Bearer YOUR_API_KEY
```

### Code Examples

<CodeGroup>
  ```javascript JavaScript theme={null}
  const axios = require('axios');

  const API_KEY = process.env.SNIPPETS_AI_API_KEY;
  const BASE_URL = 'https://www.getsnippets.ai/api/prompts';

  // Configure axios with default headers
  const api = axios.create({
  	baseURL: BASE_URL,
  	headers: {
  		Authorization: `Bearer ${API_KEY}`,
  		'Content-Type': 'application/json',
  	},
  });

  // Make a request
  async function getSnippet(id) {
  	const response = await api.get('/snippet', {
  		params: { id },
  	});
  	return response.data;
  }
  ```

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

  API_KEY = os.environ.get('SNIPPETS_AI_API_KEY')
  BASE_URL = 'https://www.getsnippets.ai/api/prompts'

  # Create a session with default headers
  session = requests.Session()
  session.headers.update({
      'Authorization': f'Bearer {API_KEY}',
      'Content-Type': 'application/json'
  })

  # Make a request
  def get_snippet(snippet_id):
      response = session.get(
          f'{BASE_URL}/snippet',
          params={'id': snippet_id}
      )
      return response.json()
  ```

  ```bash cURL theme={null}
  # Store your API key in an environment variable
  export SNIPPETS_AI_API_KEY="your_api_key_here"

  # Make a request
  curl -X GET "https://www.getsnippets.ai/api/prompts/snippet?id=snippet_id" \
    -H "Authorization: Bearer $SNIPPETS_AI_API_KEY" \
    -H "Content-Type: application/json"
  ```

  ```php PHP theme={null}
  <?php

  $apiKey = getenv('SNIPPETS_AI_API_KEY');
  $baseUrl = 'https://www.getsnippets.ai/api/prompts';

  // Using cURL
  function getSnippet($snippetId) {
      global $apiKey, $baseUrl;

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "$baseUrl/snippet?id=$snippetId");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
          "Authorization: Bearer $apiKey",
          "Content-Type: application/json"
      ]);

      $response = curl_exec($ch);
      curl_close($ch);

      return json_decode($response, true);
  }
  ?>
  ```
</CodeGroup>

## Team Permissions

API keys can be configured with different levels of access:

### All Teams Access

When enabled, the API key has access to all teams in your workspace, including newly created teams.

```json theme={null}
{
	"is_all_teams": true,
	"team_permissions": []
}
```

### Specific Team Access

Limit the API key to specific teams for better security:

```json theme={null}
{
	"is_all_teams": false,
	"team_permissions": ["team_uuid_1", "team_uuid_2"]
}
```

<Note>
  If you try to access a resource (snippet, folder, or tag) from a team that
  your API key doesn't have permission for, you'll receive a `403 Forbidden`
  error.
</Note>

## Security Best Practices

<AccordionGroup>
  <Accordion title="Use Environment Variables">
    Never hardcode API keys in your source code. Use environment variables or secure secret management systems:

    ```bash theme={null}
    # .env file
    SNIPPETS_AI_API_KEY=your_api_key_here
    ```
  </Accordion>

  {' '}

  <Accordion title="Rotate Keys Regularly">
    Periodically rotate your API keys, especially if: - A team member with access
    leaves - You suspect a key may have been compromised - You're decommissioning
    an integration
  </Accordion>

  {' '}

  <Accordion title="Use Minimum Required Permissions">
    Create API keys with access only to the teams they need. Don't use all-teams
    access unless necessary.
  </Accordion>

  {' '}

  <Accordion title="Monitor API Usage">
    Regularly check your API usage in the dashboard to detect any unusual activity
    or unauthorized access.
  </Accordion>

  <Accordion title="Use HTTPS Only">
    Always make API requests over HTTPS. The API will reject requests made over plain HTTP.
  </Accordion>
</AccordionGroup>

## Managing API Keys

### Viewing API Keys

You can view all your API keys in the dashboard, including:

* Key name and creation date
* Last used timestamp
* Team permissions
* Active/inactive status

### Deactivating Keys

To deactivate an API key:

1. Go to Settings → API Keys
2. Find the key you want to deactivate
3. Click **Deactivate**

<Warning>
  Deactivated keys will immediately stop working. Any integrations using that
  key will start receiving `401 Unauthorized` errors.
</Warning>

### Deleting Keys

To permanently delete an API key:

1. First deactivate the key
2. Wait at least 24 hours (recommended)
3. Click **Delete** to permanently remove it

## Authentication Errors

Common authentication errors and how to resolve them:

<ResponseField name="401 Unauthorized" type="error">
  **Invalid or inactive API key**

  Your API key is either invalid, has been deactivated, or was never created.

  ```json theme={null}
  {
    "success": false,
    "message": "Invalid or inactive API key"
  }
  ```

  **Solution**: Verify your API key is correct and active in the dashboard.
</ResponseField>

<ResponseField name="401 Unauthorized" type="error">
  **Missing Authorization header**

  The request didn't include an Authorization header.

  ```json theme={null}
  {
    "success": false,
    "message": "Authorization header with Bearer token is required"
  }
  ```

  **Solution**: Ensure you're including `Authorization: Bearer YOUR_API_KEY` in all requests.
</ResponseField>

<ResponseField name="403 Forbidden" type="error">
  **Insufficient permissions**

  Your API key doesn't have access to the requested team.

  ```json theme={null}
  {
    "success": false,
    "message": "API key does not have access to this team"
  }
  ```

  **Solution**: Update your API key's team permissions or use a different key.
</ResponseField>

<ResponseField name="403 Forbidden" type="error">
  **Inactive subscription**

  Your workspace subscription is not active.

  ```json theme={null}
  {
    "success": false,
    "message": "Workspace subscription is not active"
  }
  ```

  **Solution**: Check your subscription status and update your billing information.
</ResponseField>

## Testing Your Authentication

Use this simple request to verify your API key is working:

```bash theme={null}
curl -X GET "https://www.getsnippets.ai/api/prompts/snippet?id=test" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

If authentication is successful but the snippet doesn't exist, you'll receive a `404 Not Found` error (which confirms authentication worked). If authentication fails, you'll receive a `401 Unauthorized` error.

## Need Help?

If you're having trouble with authentication:

<CardGroup cols={2}>
  <Card title="Contact Support" icon="life-ring" href="mailto:team@getsnippets.ai">
    Get help from our team
  </Card>
</CardGroup>
