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

# Authentication

> Learn how to authenticate your API requests to Haystack

## Overview

The Haystack API uses **Bearer token authentication** to secure API requests. Most API endpoints require a valid authentication token in the `Authorization` header.

<Warning>
  **Search Endpoint Exception**: The [Search endpoint](/api-reference/endpoints/search) does NOT require authentication. It is designed to be called from public-facing websites and applications. **Never include your API token** when calling the search endpoint, as this would expose your credentials to end users.
</Warning>

## Two Types of API Access

Haystack provides two separate APIs for different use cases:

### Search API (Public, No Authentication)

* **Purpose**: Search your content library from anywhere, including public websites
* **Authentication**: None required
* **Base URL**: `https://{your-church-shortname}.thehaystack.ai/api`
* **Use from**: Frontend JavaScript, mobile apps, any public-facing application

### Private API (Authenticated)

* **Purpose**: Manage your library, access analytics, update settings
* **Authentication**: API key required (Bearer token)
* **Base URL**: `https://api.thehaystack.ai/v2/haystack`
* **Use from**: Backend servers only (never from frontend code)

## Getting Your Search API Base URL

The Search API base URL is specific to your organization:

1. Log in to your [Haystack Dashboard](https://app.thehaystack.ai)
2. Navigate to **Developer** → **API**
3. Find your **Search API Base URL** in the Search API section
4. Click **Copy** to copy the URL to your clipboard

Your Search API base URL will look like:

```
https://your-church-name.thehaystack.ai/api
```

<Note>
  The Search API does not require authentication. You can use it directly from frontend JavaScript without exposing any credentials.
</Note>

## Getting Your Private API Token

To create a Private API token for authenticated requests:

1. Log in to your [Haystack Dashboard](https://app.thehaystack.ai)
2. Navigate to **Developer** → **API**
3. In the **Private API** section, click **New key**
4. Enter a descriptive name for your key (e.g., "Production Server")
5. Choose whether to enable **Admin privileges** (only if needed for user/billing management)
6. Click **Submit**
7. **Important**: Copy your API key immediately - you won't be able to see it again!

<Warning>
  **Keep Your API Key Private**: This key provides access to your Haystack account. Never share it, expose it in frontend code, or commit it to version control. Store it securely using environment variables or a secrets manager.
</Warning>

## Making Authenticated Requests (Private API)

For Private API endpoints, include your API token in the `Authorization` header using the Bearer authentication scheme:

```bash theme={null}
Authorization: Bearer YOUR_API_TOKEN
```

### Example Private API Request

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.thehaystack.ai/v2/haystack/items \
    -H "Authorization: Bearer YOUR_API_TOKEN" \
    -H "Content-Type: application/json"
  ```

  ```javascript JavaScript theme={null}
  const API_URL = 'https://api.thehaystack.ai/v2/haystack';
  const API_TOKEN = process.env.HAYSTACK_API_TOKEN;

  const response = await fetch(`${API_URL}/items`, {
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  ```

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

  API_URL = 'https://api.thehaystack.ai/v2/haystack'
  API_TOKEN = os.getenv('HAYSTACK_API_TOKEN')

  headers = {
      'Authorization': f'Bearer {API_TOKEN}',
      'Content-Type': 'application/json'
  }

  response = requests.get(f'{API_URL}/items', headers=headers)
  data = response.json()
  ```

  ```typescript TypeScript theme={null}
  const API_URL = 'https://api.thehaystack.ai/v2/haystack';
  const API_TOKEN = process.env.HAYSTACK_API_TOKEN;

  const response = await fetch(`${API_URL}/items`, {
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  ```
</CodeGroup>

### Example Search API Request (No Authentication)

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://your-church-name.thehaystack.ai/api/haystack/search?q=prayer"
  ```

  ```javascript JavaScript theme={null}
  const SEARCH_API_URL = 'https://your-church-name.thehaystack.ai/api';

  const response = await fetch(
    `${SEARCH_API_URL}/haystack/search?q=${encodeURIComponent('prayer')}`,
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );

  const data = await response.json();
  ```

  ```python Python theme={null}
  SEARCH_API_URL = 'https://your-church-name.thehaystack.ai/api'

  params = {'q': 'prayer'}
  response = requests.get(f'{SEARCH_API_URL}/haystack/search', params=params)
  data = response.json()
  ```

  ```typescript TypeScript theme={null}
  const SEARCH_API_URL = 'https://your-church-name.thehaystack.ai/api';

  const response = await fetch(
    `${SEARCH_API_URL}/haystack/search?q=${encodeURIComponent('prayer')}`,
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );

  const data = await response.json();
  ```
</CodeGroup>

## Which API Should I Use?

Choose the appropriate API based on where your code runs:

| Scenario                      | API to Use  | Base URL                                      | Authentication   |
| ----------------------------- | ----------- | --------------------------------------------- | ---------------- |
| Search from website           | Search API  | `https://{your-shortname}.thehaystack.ai/api` | None             |
| Search from mobile app        | Search API  | `https://{your-shortname}.thehaystack.ai/api` | None             |
| Manage content from backend   | Private API | `https://api.thehaystack.ai/v2/haystack`      | API Key required |
| Upload media from backend     | Private API | `https://api.thehaystack.ai/v2/haystack`      | API Key required |
| Access analytics from backend | Private API | `https://api.thehaystack.ai/v2/haystack`      | API Key required |

<Warning>
  **Never use Private API keys in frontend code**. API keys should only be used from backend servers where they can be kept secure. For public-facing search functionality, use the Search API which requires no authentication.
</Warning>

## Authentication Errors

The API returns specific error responses for authentication issues:

### 401 Unauthorized

Returned when your API token is missing, invalid, or expired.

```json theme={null}
{
  "result": "error",
  "error": {
    "type": "Unauthorized",
    "message": "Invalid or missing authentication token"
  }
}
```

**Resolution**: Verify your token is correct and included in the `Authorization` header.

### 403 Forbidden

Returned when your token is valid but you don't have permission to access the requested resource.

```json theme={null}
{
  "result": "error",
  "error": {
    "type": "Forbidden",
    "message": "Insufficient permissions to access this resource"
  }
}
```

**Resolution**: Ensure your API token has the necessary permissions for the resource you're trying to access.

## Next Steps

Now that you understand authentication, you're ready to make your first API call:

<Card title="Quickstart Guide" icon="rocket" href="/quickstart" horizontal>
  Follow our quickstart tutorial to make your first authenticated API request
</Card>
