> ## 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.

# Quick Start

> Get started with the Haystack API in 5 minutes

## Overview

This guide will walk you through making your first API calls to Haystack. You'll learn how to authenticate, retrieve content, and perform a search.

**1. Get Your API Credentials**

Haystack provides two APIs. Get the credentials you need from the [Haystack Dashboard](https://app.thehaystack.ai):

**For the Private API** (content management, analytics):

1. Navigate to **Developer** → **API**
2. In the **Private API** section, click **New key**
3. Enter a name (e.g., "Development Server") and click **Submit**
4. Copy and save your API key securely (you won't see it again!)

**For the Search API** (public search, no authentication):

1. Navigate to **Developer** → **API**
2. In the **Search API** section, find your **Search API Base URL**
3. Click **Copy** to copy your church-specific URL

> [!WARNING]
>
> Keep your Private API key secure. Never use it in frontend code or commit it to version control.

**2. Set Up Your Environment**

Store your credentials as environment variables:

```bash theme={null}
# Private API (for backend use only)
export HAYSTACK_API_TOKEN="sk_..."
export HAYSTACK_API_URL="https://api.thehaystack.ai/v2/haystack"

# Search API (for frontend/public use)
export HAYSTACK_SEARCH_URL="https://your-church-name.thehaystack.ai/api"
```

Or create a `.env` file:

```bash .env theme={null}
# Private API (backend only)
HAYSTACK_API_TOKEN=sk_...
HAYSTACK_API_URL=https://api.thehaystack.ai/v2/haystack

# Search API (frontend safe)
HAYSTACK_SEARCH_URL=https://your-church-name.thehaystack.ai/api
```

**3. Make Your First Request**

Let's retrieve your collections to verify authentication is working:

```bash cURL theme={null}
curl "$HAYSTACK_API_URL/collections" \
  -H "Authorization: Bearer $HAYSTACK_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;

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

  const data = await response.json();
  console.log('Collections:', data.collections);
  return data;
}

getCollections();
```

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

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

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

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

    print('Collections:', data['collections'])
    return data

get_collections()
```

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

interface Collection {
  id: number;
  name: string;
  customerId: number;
}

interface CollectionsResponse {
  collections: Collection[];
  total: number;
  page: number;
  pageSize: number;
}

async function getCollections(): Promise<CollectionsResponse> {
  const response = await fetch(`${API_URL}/collections`, {
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    }
  });

  const data = await response.json();
  console.log('Collections:', data.collections);
  return data;
}

getCollections();
```

**Expected Response:**

```json theme={null}
{
  "collections": [
    {
      "id": 1,
      "name": "Sermons",
      "itemDescriptor": "sermon"
    }
  ],
  "total": 1,
  "page": 1,
  "pageSize": 20
}
```

**4. Search Your Content**

Now let's perform a search query to find content:

> [!NOTE]
>
> **No Authentication Required**: The search endpoint uses your church-specific Search API URL and does not require authentication. It's safe to call from public websites.

```bash cURL theme={null}
curl "$HAYSTACK_SEARCH_URL/haystack/search?q=leadership"
```

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

async function searchContent(query) {
  const response = await fetch(
    `${SEARCH_URL}/haystack/search?q=${encodeURIComponent(query)}`,
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );

  const data = await response.json();
  console.log('Search results:', data.items);
  return data;
}

searchContent('leadership');
```

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

SEARCH_URL = 'https://your-church-name.thehaystack.ai/api'

def search_content(query):
    params = {'q': query}

    response = requests.get(
        f'{SEARCH_URL}/haystack/search',
        params=params
    )

    data = response.json()
    print('Search results:', data['items'])
    return data

search_content('leadership')
```

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

interface SearchResult {
  item: {
    id: number;
    title: string;
    description: string;
  };
  score: number;
  highlights: Array<{
    transcript: string;
    startMs: number;
    endMs: number;
  }>;
}

interface SearchResponse {
  query: string;
  queryAnalyticsId: string;
  items: SearchResult[];
  scriptures: any[];
  series: any[];
}

async function searchContent(query: string): Promise<SearchResponse> {
  const response = await fetch(
    `${SEARCH_URL}/haystack/search?q=${encodeURIComponent(query)}`,
    {
      headers: {
        'Content-Type': 'application/json'
      }
    }
  );

  const data = await response.json();
  console.log('Search results:', data.items);
  return data;
}

searchContent('leadership');
```

> [!TIP]
>
> **Want AI-generated search overviews?** Add `&stream=true` to receive a streaming response with an AI summary of results. See the [Search endpoint documentation](https://developer.thehaystack.ai/api-reference/endpoints/search.md#streaming-response-with-ai-overview-advanced) for details.

**Expected Response:**

```json theme={null}
{
  "query": "leadership",
  "queryAnalyticsId": "abc123",
  "items": [
    {
      "item": {
        "id": 42,
        "title": "Servant Leadership",
        "description": "A message about leading with humility"
      },
      "score": 0.89,
      "highlights": [
        {
          "transcript": "Great leaders understand that leadership is about serving others...",
          "startMs": 45000,
          "endMs": 52000
        }
      ]
    }
  ],
  "scriptures": [],
  "series": []
}
```

**5. Create Content**

Let's create a new item in your library:

```bash cURL theme={null}
curl -X POST "$HAYSTACK_API_URL/items/create" \
  -H "Authorization: Bearer $HAYSTACK_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Getting Started with Haystack",
    "date": "2025-01-15",
    "collectionId": 1,
    "description": "An introduction to using Haystack API"
  }'
```

```javascript JavaScript theme={null}
async function createItem() {
  const response = await fetch(`${API_URL}/items/create`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'Getting Started with Haystack',
      date: '2025-01-15',
      collectionId: 1,
      description: 'An introduction to using Haystack API'
    })
  });

  const data = await response.json();
  console.log('Created item:', data.item);
  return data;
}

createItem();
```

```python Python theme={null}
def create_item():
    headers = {
        'Authorization': f'Bearer {API_TOKEN}',
        'Content-Type': 'application/json'
    }

    payload = {
        'title': 'Getting Started with Haystack',
        'date': '2025-01-15',
        'collectionId': 1,
        'description': 'An introduction to using Haystack API'
    }

    response = requests.post(
        f'{API_URL}/items/create',
        headers=headers,
        json=payload
    )

    data = response.json()
    print('Created item:', data['item'])
    return data

create_item()
```

```typescript TypeScript theme={null}
interface CreateItemPayload {
  title: string;
  date: string;
  collectionId: number;
  description?: string;
  subTitle?: string;
}

async function createItem(itemData: CreateItemPayload) {
  const response = await fetch(`${API_URL}/items/create`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(itemData)
  });

  const data = await response.json();
  console.log('Created item:', data.item);
  return data;
}

createItem({
  title: 'Getting Started with Haystack',
  date: '2025-01-15',
  collectionId: 1,
  description: 'An introduction to using Haystack API'
});
```

**Expected Response:**

```json theme={null}
{
  "item": {
    "id": 100,
    "title": "Getting Started with Haystack",
    "date": "2025-01-15",
    "collectionId": 1,
    "description": "An introduction to using Haystack API",
    "status": "draft"
  }
}
```

## Error Handling

Always check for errors in API responses. The API uses standard HTTP status codes:

```javascript theme={null}
async function makeApiRequest(url, options) {
  const response = await fetch(url, options);

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`API Error: ${error.error.message}`);
  }

  return response.json();
}
```

Common HTTP status codes:

* `200` - Success
* `400` - Bad Request (invalid parameters)
* `401` - Unauthorized (invalid or missing token)
* `403` - Forbidden (insufficient permissions)
* `404` - Not Found
* `500` - Internal Server Error

## Next Steps

Congratulations! You've made your first API calls to Haystack. Here's what to explore next:

> [card] [Content Model](https://developer.thehaystack.ai/concepts/content-model.md)
>
> Learn about items, collections, series, and how they relate

> [card] [Media Management](https://developer.thehaystack.ai/concepts/media-management.md)
>
> Upload and manage video and audio files

> [card] [Search & Discovery](https://developer.thehaystack.ai/concepts/search-discovery.md)
>
> Deep dive into semantic search capabilities

> [card] [API Reference](https://developer.thehaystack.ai/api-reference/introduction.md)
>
> Explore the complete API documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.