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

<Steps>
  <Step title="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.
    </Warning>
  </Step>

  <Step title="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
    ```
  </Step>

  <Step title="Make Your First Request">
    Let's retrieve your collections to verify authentication is working:

    <CodeGroup>
      ```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();
      ```
    </CodeGroup>

    **Expected Response:**

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

  <Step title="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.
    </Note>

    <CodeGroup>
      ```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');
      ```
    </CodeGroup>

    <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](/api-reference/endpoints/search#streaming-response-with-ai-overview-advanced) for details.
    </Tip>

    **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": []
    }
    ```
  </Step>

  <Step title="Create Content">
    Let's create a new item in your library:

    <CodeGroup>
      ```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'
      });
      ```
    </CodeGroup>

    **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"
      }
    }
    ```
  </Step>
</Steps>

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

<CardGroup cols={2}>
  <Card title="Content Model" icon="folder-tree" href="/concepts/content-model">
    Learn about items, collections, series, and how they relate
  </Card>

  <Card title="Media Management" icon="video" href="/concepts/media-management">
    Upload and manage video and audio files
  </Card>

  <Card title="Search & Discovery" icon="magnifying-glass" href="/concepts/search-discovery">
    Deep dive into semantic search capabilities
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the complete API documentation
  </Card>
</CardGroup>
