> 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-power-automate.md).

# How to Integrate with Power Automate

Learn how to use the SnackPrompt AI Engine API to build powerful automations and AI-powered flows in Microsoft Power Automate.

### Overview

Power Automate (formerly Microsoft Flow) offers several ways to integrate external APIs:

| Method               | Use Case             | Description                                        |
| -------------------- | -------------------- | -------------------------------------------------- |
| **HTTP Action**      | Direct API calls     | Make HTTP requests to any API                      |
| **Custom Connector** | Reusable integration | Create a connector for your organization           |
| **AI Builder**       | AI integration       | Combine with Microsoft AI capabilities             |
| **Copilot Studio**   | Chatbots             | Build intelligent chatbots with external knowledge |

### Integration Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    Power Automate                       │
│  ┌─────────────┐    ┌─────────────┐    ┌────────────┐   │
│  │   Trigger   │───▶│ HTTP Action │───▶│   Action  │   │
│  └─────────────┘    └──────┬──────┘    └────────────┘   │
│                            │                            │
│                     ┌──────▼──────┐                     │
│                     │   Parse     │                     │
│                     │    JSON     │                     │
│                     └──────┬──────┘                     │
└────────────────────────────┼────────────────────────────┘
                             │
                             ▼
              ┌──────────────────────────────┐
              │  SnackPrompt AI Engine API   │
              │  /v1/kb/search or /v1/kb/chat│
              └──────────────────────────────┘
```

***

### Method 1: HTTP Action (Recommended)

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

#### Step 1: Create a New Flow

1. Go to [make.powerautomate.com](https://make.powerautomate.com)
2. Click **Create** > **Automated cloud flow** or **Instant cloud flow**
3. Choose your trigger (e.g., When an email arrives, When an item is created)

#### Step 2: Add HTTP Action

1. Click **+ New step**
2. Search for **HTTP**
3. Select **HTTP** (not HTTP + Swagger)

#### Step 3: Configure the Request

**For Search Endpoint:**

<table><thead><tr><th width="195">Field</th><th>Value</th></tr></thead><tbody><tr><td>Method</td><td><code>POST</code></td></tr><tr><td>URI</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`    | `@{variables('ApiKey')}` or your key |

**Body:**

```json
{
  "query": "@{triggerBody()?['subject']}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  },
  "limit": 5
}
```

#### Step 4: Parse the Response

Add **Parse JSON** action after HTTP:

1. Click **+ New step**
2. Search for **Parse JSON**
3. **Content**: Select the Body from HTTP action
4. **Schema**: Click "Generate from sample" and paste:

```json
{
  "items": [
    {
      "payload": {
        "original_text": "Sample text",
        "snack_item_id": "item_123"
      },
      "score": 0.95
    }
  ]
}
```

#### Step 5: Use the Results

Now you can use the parsed results in subsequent actions:

* `@{body('Parse_JSON')?['items']}` - All items
* `@{first(body('Parse_JSON')?['items'])?['payload']?['original_text']}` - First result text

***

### Method 2: Chat Endpoint for Complete Responses

Use the `/v1/kb/chat` endpoint when you want the **API to handle all the RAG**.

#### HTTP Configuration

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

**Headers:**

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

**Body:**

```json
{
  "query": "@{triggerBody()?['message']}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID",
    "tag_names": ["Support", "FAQ"]
  }
}
```

#### Response

The API returns:

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

Access with: `@{body('HTTP')?['answer']}`

***

### Method 3: Custom Connector (Reusable)

Create a custom connector for your organization to simplify reuse.

#### Step 1: Create Custom Connector

1. Go to **Data** > **Custom connectors**
2. Click **+ New custom connector** > **Create from blank**

#### Step 2: General Information

| Field          | Value                                 |
| -------------- | ------------------------------------- |
| Connector name | `SnackPrompt AI Engine`               |
| Host           | `integrations.api.snackprompt.com.br` |
| Base URL       | `/v1/kb`                              |

#### Step 3: Security

| Field               | Value       |
| ------------------- | ----------- |
| Authentication type | `API Key`   |
| Parameter label     | `API Key`   |
| Parameter name      | `x-api-key` |
| Parameter location  | `Header`    |

#### Step 4: Definition - Search Action

**General:**

| Field        | Value                   |
| ------------ | ----------------------- |
| Summary      | `Search Knowledge Base` |
| Operation ID | `SearchKnowledgeBase`   |

**Request:**

* Method: `POST`
* URL: `/search`

**Body Parameters:**

| Name       | Type    | Required | Description    |
| ---------- | ------- | -------- | -------------- |
| query      | string  | Yes      | Search query   |
| tenant\_id | string  | Yes      | Tenant ID      |
| tag\_names | array   | No       | Filter by tags |
| limit      | integer | No       | Max results    |

#### Step 5: Definition - Chat Action

**General:**

| Field        | Value                      |
| ------------ | -------------------------- |
| Summary      | `Chat with Knowledge Base` |
| Operation ID | `ChatWithKnowledgeBase`    |

**Request:**

* Method: `POST`
* URL: `/chat`

#### Step 6: Create and Test

1. Click **Create connector**
2. Go to **Test** tab
3. Create a new connection with your API key
4. Test both operations

#### Step 7: Use in Flows

The connector now appears under your custom connectors:

```
[Trigger] → [SnackPrompt: Search Knowledge Base] → [Action]
```

***

### Method 4: Integration with Copilot Studio

Build chatbots that use your knowledge base.

#### Step 1: Create a Power Automate Flow

Create a flow that can be called from Copilot Studio:

1. Create **Instant cloud flow**
2. Trigger: **When Power Virtual Agents calls a flow**
3. Add **HTTP** action to call SnackPrompt API
4. Add **Return value(s) to Power Virtual Agents**

#### Step 2: Configure Flow

**Input from Copilot:**

* `UserQuestion` (text) - The user's question

**HTTP Action:**

```json
{
  "query": "@{triggerBody()?['text']}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID"
  }
}
```

**Return to Copilot:**

* `Answer`: `@{body('HTTP')?['answer']}`
* `Sources`: `@{body('HTTP')?['sources']}`

#### Step 3: Connect in Copilot Studio

1. In your Copilot, create a new Topic
2. Add **Call an action** > Select your flow
3. Pass the user's message
4. Display the returned answer

***

### Practical Use Cases

#### 1. Email Auto-Responder

```
[When email arrives] → [HTTP: /chat] → [Send reply email]
```

Automatically respond to customer emails using knowledge base.

#### 2. Teams Bot Integration

```
[When message in Teams] → [HTTP: /search] → [Post reply in Teams]
```

Answer questions posted in Microsoft Teams channels.

#### 3. SharePoint Document Assistant

```
[When item created in SharePoint] → [HTTP: /search] → [Update item with related docs]
```

Automatically find and link related documents.

#### 4. Forms Response Handler

```
[When Forms response submitted] → [HTTP: /chat] → [Send email with answer]
```

Process form questions and send personalized responses.

#### 5. Scheduled Knowledge Report

```
[Recurrence: Weekly] → [HTTP: /search] → [Create Excel row] → [Send email]
```

Generate weekly reports from knowledge base queries.

#### 6. Multi-Step Support Flow

```
[When email arrives]
        │
        ▼
[HTTP: /search]
        │
        ▼
[Condition: items length > 0]
        │
    ┌───┴───┐
    │       │
   Yes      No
    │       │
    ▼       ▼
[Reply]  [Create Planner task]
```

***

### Working with Variables

#### Store API Key Securely

Use **Environment Variables** or **Azure Key Vault**:

**Option 1: Environment Variables**

1. Go to **Solutions**
2. Add **Environment variable**
3. Name: `SnackPromptApiKey`
4. Reference: `@{parameters('SnackPromptApiKey')}`

**Option 2: Azure Key Vault**

1. Add **Azure Key Vault** connector
2. **Get secret** action
3. Use secret value in HTTP header

#### Initialize Variables

At the start of your flow:

```
[Initialize variable: ApiKey]
[Initialize variable: TenantId]
```

Reference in HTTP body:

```json
{
  "filters": {
    "tenant_id": "@{variables('TenantId')}"
  }
}
```

***

### Configuration Tips

#### 1. Use Expressions for Dynamic Values

```
@{if(empty(triggerBody()?['category']),
     json('[]'),
     createArray(triggerBody()?['category']))}
```

#### 2. Handle Empty Results

Add a **Condition** after Parse JSON:

```
Condition: length(body('Parse_JSON')?['items']) is greater than 0
```

#### 3. Limit Results for Efficiency

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

#### 4. Error Handling

Configure **Run after** settings:

1. Click **...** on the action after HTTP
2. Select **Configure run after**
3. Check **has failed** to handle errors

Or use **Scope** with **Try-Catch** pattern:

```
[Scope: Try]
    └── [HTTP Action]
    └── [Process Results]
[Scope: Catch] (Run after: Try has failed)
    └── [Send error notification]
```

#### 5. Apply to Each for Multiple Results

When processing all results:

```
[Apply to each: items]
    └── Current item: @{items('Apply_to_each')?['payload']?['original_text']}
```

***

### Complete Example: Support Ticket Automation

#### Flow Overview

1. Email arrives with support question
2. Search knowledge base for answer
3. If found, send automated reply
4. If not found, create support ticket in Planner

#### Step-by-Step

**Trigger: When a new email arrives (V3)**

* Folder: Inbox
* Include Attachments: No

**Action 1: HTTP**

```
Method: POST
URI: https://api-integrations.snackprompt.com/v1/kb/chat
Headers:
  Content-Type: application/json
  x-api-key: YOUR_API_KEY
Body:
{
  "query": "@{triggerBody()?['subject']} @{triggerBody()?['bodyPreview']}",
  "filters": {
    "tenant_id": "YOUR_TENANT_ID",
    "tag_names": ["Support"]
  }
}
```

**Action 2: Parse JSON**

* Content: `@{body('HTTP')}`
* Schema: (generate from sample response)

**Action 3: Condition**

* `@{length(body('Parse_JSON')?['sources'])}` is greater than `0`

**If Yes - Send Email (V2)**

* To: `@{triggerBody()?['from']}`
* Subject: `Re: @{triggerBody()?['subject']}`
* Body: `@{body('Parse_JSON')?['answer']}`

**If No - Create Task (Planner)**

* Title: `Support: @{triggerBody()?['subject']}`
* Details: `@{triggerBody()?['body']}`

***

### Expressions Reference

#### Common Expressions

| Expression                                    | Description                |
| --------------------------------------------- | -------------------------- |
| `@{body('HTTP')}`                             | Full HTTP response body    |
| `@{body('HTTP')?['answer']}`                  | Answer field from response |
| `@{first(body('Parse_JSON')?['items'])}`      | First item from array      |
| `@{length(body('Parse_JSON')?['items'])}`     | Count of items             |
| `@{join(body('Parse_JSON')?['items'], ', ')}` | Join items as string       |

#### Working with Arrays

```
// Get first result text
@{first(body('Parse_JSON')?['items'])?['payload']?['original_text']}

// Get all texts as array
@{body('Parse_JSON')?['items']?['payload']?['original_text']}

// Check if has results
@{greater(length(body('Parse_JSON')?['items']), 0)}
```

***

### Troubleshooting

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

Ensure `tenant_id` is inside the `filters` object:

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

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

#### Error: "InvalidJson" in Parse JSON

1. Check HTTP response is valid JSON
2. Verify schema matches actual response
3. Add **Compose** action before Parse JSON to debug:
   * Input: `@{body('HTTP')}`

#### HTTP Action Fails

1. Check URI is correct (no extra spaces)
2. Verify headers are properly formatted
3. Test API with Postman first
4. Check firewall/network access

#### Empty Results

1. Verify tenant\_id is correct
2. Remove tag\_names filter to search all content
3. Increase limit parameter
4. Test query directly in API

#### Flow Runs Slowly

1. Reduce limit parameter
2. Use parallel branches where possible
3. Consider using async patterns for long operations

***

### Premium vs Standard Licensing

The **HTTP** action requires a **Premium** license. Alternatives for Standard:

| Feature           | Premium | Standard Alternative                     |
| ----------------- | ------- | ---------------------------------------- |
| HTTP Action       | ✅       | Use Custom Connector (also Premium)      |
| Custom Connectors | ✅       | Request IT to create certified connector |
| Azure Functions   | ✅       | Azure Functions with Standard trigger    |

***

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

* [Power Automate Documentation](https://docs.microsoft.com/en-us/power-automate/)
* [HTTP Action Reference](https://docs.microsoft.com/en-us/power-automate/http-action)
* [Custom Connectors Guide](https://docs.microsoft.com/en-us/connectors/custom-connectors/)
* [Copilot Studio Documentation](https://docs.microsoft.com/en-us/power-virtual-agents/)
* [Expression Reference](https://docs.microsoft.com/en-us/azure/logic-apps/workflow-definition-language-functions-reference)


---

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