> For the complete documentation index, see [llms.txt](https://docs.snackprompt.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.snackprompt.com/bring-your-data-into-ai/how-to/get-started-with-integrations/how-to-integrate-with-zapier.md).

# How to Integrate with Zapier

Learn how to use the SnackPrompt AI Engine API to build powerful automations and AI-powered workflows in Zapier.

### Overview

Zapier offers several ways to integrate external APIs into your automations:

| Method                 | Use Case            | Description                             |
| ---------------------- | ------------------- | --------------------------------------- |
| **Webhooks by Zapier** | Receive data        | Trigger Zaps when external events occur |
| **API Request (Beta)** | Direct API calls    | Make HTTP requests to any API           |
| **Code by Zapier**     | Advanced processing | Run JavaScript/Python to process data   |
| **Chatbots by Zapier** | AI conversations    | Build chatbots with custom knowledge    |

### Integration Architecture

```
┌─────────────────────────────────────────────────────────┐
│                       Zapier                            │
│  ┌─────────────┐    ┌─────────────┐    ┌────────────┐   │
│  │   Trigger   │───▶│  API Request│───▶│   Action  │   │
│  └─────────────┘    └──────┬──────┘    └────────────┘   │
│                            │                            │
│                     ┌──────▼──────┐                     │
│                     │ Code Step   │                     │
│                     │ (optional)  │                     │
│                     └──────┬──────┘                     │
└────────────────────────────┼────────────────────────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │  SnackPrompt AI Engine API   │
              │  /v1/kb/search or /v1/kb/chat│
              └──────────────────────────────┘
```

***

### Method 1: API Request (Recommended)

Use the **API Request** action to call the SnackPrompt AI Engine API directly.

#### Step 1: Create a New Zap

1. Go to [zapier.com](https://zapier.com) and click **Create Zap**
2. Choose your trigger (e.g., New Email, New Form Submission, Schedule)

#### Step 2: Add API Request Action

1. Click **+** to add a new action
2. Search for **API Request (Beta)** or **Webhooks by Zapier**
3. Select **Custom Request**

#### Step 3: Configure the Request

**For Search Endpoint:**

<table><thead><tr><th width="237">Field</th><th>Value</th></tr></thead><tbody><tr><td>Method</td><td><code>POST</code></td></tr><tr><td>URL</td><td><code>https://api-integrations.snackprompt.com/v1/kb/search</code></td></tr></tbody></table>

**Headers:**

| Key            | Value              |
| -------------- | ------------------ |
| `Content-Type` | `application/json` |
| `x-api-key`    | `YOUR_API_KEY`     |

**Body:**

```json
{
  "query": "{{trigger_field}}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

Replace `{{trigger_field}}` with the field from your trigger that contains the search query.

#### Step 4: Use the Results

The API returns a list of relevant documents. You can use the results in subsequent actions:

* Send an email with the information found
* Update a CRM record
* Post to Slack
* Create a support ticket

***

### Method 2: Webhooks by Zapier (Receive Requests)

Use when you want to **receive requests** and respond with knowledge base information.

#### Step 1: Create Webhook Trigger

1. Create a new Zap
2. Select **Webhooks by Zapier** as trigger
3. Choose **Catch Hook**
4. Copy the webhook URL provided

#### Step 2: Add API Request Action

Configure as shown in Method 1, using the data from the webhook:

**Body:**

```json
{
  "query": "{{catch_hook_query}}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

#### Step 3: Return Response (Optional)

If you need to return a response to the webhook caller:

1. Add **Webhooks by Zapier** action
2. Select **Return Response**
3. Configure the response body with the API results

***

### Method 3: Chat Endpoint for Complete Responses

Use the `/v1/kb/chat` endpoint when you want the **API to handle all the RAG** and return a ready response.

#### Configuration

**URL:**

```
https://api-integrations.snackprompt.com/v1/kb/chat
```

**Headers:**

| Key            | Value              |
| -------------- | ------------------ |
| `Content-Type` | `application/json` |
| `x-api-key`    | `YOUR_API_KEY`     |

**Body:**

```json
{
  "query": "{{trigger_field}}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID",
    "tag_names": ["Support", "FAQ"]
  }
}
```

#### Response

The API returns:

* `answer`: AI-generated response ready to use
* `sources`: Sources used to generate the response

***

### Method 4: Code by Zapier (Advanced)

Use when you need to **process or transform** the API response.

#### Step 1: Add Code Step

1. Add **Code by Zapier** action
2. Choose **Run JavaScript** or **Run Python**

#### Step 2: JavaScript Example

**Input Data:**

* `query`: The search query from trigger
* `api_key`: Your API key
* `tenant_id`: Your tenant ID

**Code:**

```javascript
const response = await fetch('https://api-integrations.snackprompt.com/v1/kb/search', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': inputData.api_key
  },
  body: JSON.stringify({
    query: inputData.query,
    filters: {
      tenant_id: inputData.tenant_id
    },
    limit: 5
  })
});

const data = await response.json();

// Format results for easy use
const formattedResults = data.items.map((item, index) => ({
  position: index + 1,
  text: item.payload.original_text,
  score: item.score,
  id: item.payload.snack_item_id
}));

output = {
  results: JSON.stringify(formattedResults),
  firstResult: formattedResults[0]?.text || 'No results found',
  resultCount: formattedResults.length
};
```

#### Step 3: Python Example

```python
import requests
import json

response = requests.post(
    'https://api-integrations.snackprompt.com/v1/kb/search',
    headers={
        'Content-Type': 'application/json',
        'x-api-key': input_data['api_key']
    },
    json={
        'query': input_data['query'],
        'filters': {
            'tenant_id': input_data['tenant_id']
        },
        'limit': 5
    }
)

data = response.json()

# Format results
results = []
for i, item in enumerate(data.get('items', [])):
    results.append({
        'position': i + 1,
        'text': item['payload']['original_text'],
        'score': item['score']
    })

output = {
    'results': json.dumps(results),
    'first_result': results[0]['text'] if results else 'No results found',
    'result_count': len(results)
}
```

***

### Practical Use Cases

#### 1. Email Auto-Responder

```
[New Email in Gmail] → [API Request: /chat] → [Send Reply with answer]
```

Automatically respond to customer emails using knowledge base information.

#### 2. Slack Support Bot

```
[New Message in Slack Channel] → [API Request: /search] → [Post Reply to Thread]
```

Answer questions posted in a support Slack channel.

#### 3. CRM Enrichment

```
[New Lead in HubSpot] → [API Request: /search] → [Update Lead with relevant docs]
```

Automatically attach relevant documentation to new leads based on their inquiry.

#### 4. Form Response Handler

```
[New Typeform Submission] → [API Request: /chat] → [Send Email with answer]
```

Process form questions and send personalized responses.

#### 5. Scheduled Knowledge Digest

```
[Schedule: Every Monday] → [API Request: /search] → [Create Notion Page]
```

Generate weekly digests of popular topics from your knowledge base.

#### 6. Multi-Step Support Flow

```
[Webhook: Receive Question]
        │
        ▼
[API Request: /search with tag=FAQ]
        │
        ▼
[Filter: Check if results found]
        │
    ┌───┴───┐
    │       │
    ▼       ▼
[Found]  [Not Found]
    │       │
    ▼       ▼
[Reply] [Create Ticket]
```

***

### Configuration Tips

#### 1. Store API Key Securely

Use Zapier's **Secret Manager** or environment variables:

1. Go to your Zap settings
2. Add a **Secret** for your API key
3. Reference it as `{{secrets.snackprompt_api_key}}`

#### 2. Use Filters Wisely

Direct searches with tags when you know the context:

```json
{
  "filters": {
    "tenant_id": "...",
    "tag_names": ["{{detected_category}}"]
  }
}
```

#### 3. Handle Empty Results

Add a **Filter** or **Paths** step after the API call:

```
[API Request] → [Filter: items length > 0] → [Send Response]
                                          ↘ [Fallback Action]
```

#### 4. Limit Results for Cost Efficiency

Start with fewer results and increase if needed:

```json
{
  "limit": 3
}
```

#### 5. Add Error Handling

Use Zapier's built-in error handling:

1. Click on your API Request step
2. Go to **Advanced Settings**
3. Enable **Continue on Error**
4. Add a **Paths** step to handle errors

***

### Complete Example: Customer Support Automation

#### Workflow Overview

1. Customer submits question via form
2. Zap searches knowledge base
3. If answer found, send automated reply
4. If not found, create support ticket

#### Step-by-Step Setup

**Step 1: Trigger - New Form Submission**

* App: Typeform, Google Forms, or Jotform
* Trigger: New Response

**Step 2: Action - API Request**

* URL: `https://api-integrations.snackprompt.com/v1/kb/chat`
* Method: POST
* Headers:

  ```
  Content-Type: application/json
  x-api-key: YOUR_API_KEY
  ```
* Body:

  ```json
  {
    "query": "{{form_question_field}}",
    "filters": {
      "tenant_id": "YOUR_TENANT_ID",
      "tag_names": ["Support"]
    }
  }
  ```

**Step 3: Paths - Check Response Quality**

* Path A: If `sources` array is not empty
* Path B: If `sources` array is empty

**Step 4A: Send Automated Reply**

* App: Gmail or your email service
* To: `{{form_email_field}}`
* Subject: `Re: {{form_subject_field}}`
* Body: `{{api_response_answer}}`

**Step 4B: Create Support Ticket**

* App: Zendesk, Freshdesk, or Linear
* Create ticket with original question

***

### Troubleshooting

#### Error: "tenant\_id is required"

Make sure `tenant_id` is inside the `filters` object:

```json
// ❌ Wrong
{ "query": "...", "tenant_id": "..." }

// ✅ Correct
{ "query": "...", "filters": { "tenant_id": "..." } }
```

#### Error: "Invalid JSON"

Check your JSON body for:

* Missing commas between fields
* Unescaped quotes in dynamic values
* Trailing commas (not allowed in JSON)

Use a **Code** step to safely construct JSON:

```javascript
output = {
  body: JSON.stringify({
    query: inputData.query,
    filters: { tenant_id: inputData.tenant_id }
  })
};
```

#### API Returns Empty Results

1. Verify your `tenant_id` is correct
2. Check if the query matches content in your knowledge base
3. Try removing `tag_names` filter to search all content
4. Increase the `limit` parameter

#### Zap Runs but No Response

1. Check the API Request step output in Zap History
2. Verify the response is being mapped correctly to the next step
3. Ensure the response fields match what you're referencing

#### Rate Limiting

If you hit rate limits:

1. Add a **Delay** step before API calls
2. Use **Zapier's built-in throttling** in Zap settings
3. Consider batching requests with **Looping by Zapier**

***

### Zapier AI Integration

#### Using with Zapier Central (AI)

Zapier Central can use the SnackPrompt API as a data source:

1. Create an **API Connection** in Zapier Central
2. Configure the search endpoint
3. Ask Central to query your knowledge base

#### Chatbots by Zapier

Build a chatbot that uses your knowledge base:

1. Create a new Chatbot
2. Add a **Custom Action** that calls the `/chat` endpoint
3. Use the response as the bot's reply

***

### Related

* [Endpoints Reference](/bring-your-data-into-ai/reference/endpoints.md)
* [Available Filters](/bring-your-data-into-ai/reference/filters.md)
* [Error Hand](/bring-your-data-into-ai/how-to/how-to-handle-errors.md)

### External Resources

* [Zapier Webhooks Documentation](https://zapier.com/apps/webhook/integrations)
* [API Request Action Docs](https://help.zapier.com/hc/en-us/articles/8496291148685-API-Request-actions)
* [Code by Zapier Guide](https://zapier.com/apps/code/integrations)
* [Zapier Paths for Conditional Logic](https://zapier.com/features/paths)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.snackprompt.com/bring-your-data-into-ai/how-to/get-started-with-integrations/how-to-integrate-with-zapier.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
