Integration with API

Waterflai API Documentation

This comprehensive guide explains how to integrate your Waterflai chatbots with external applications using our API. You'll learn how to manage API keys, understand different endpoints for synchronous and asynchronous execution, handle various content types, and implement best practices for a robust integration.

For a complete technical specification of all schemas and endpoints, please refer to our OpenAPI Reference Documentation.

API Overview

Waterflai provides different API endpoints based on your chatbot type and desired execution mode:

  • Simple Chatbots: An OpenAI-compatible endpoint for basic, non-flow-based chat interactions.

  • Dream Builder (Chatflows): Specialized endpoints for executing complex conversational flows.

  • Workflow Builder: Dedicated endpoints for running automated, multi-step workflows.

You can execute your chatbots in two ways:

  • Synchronous Execution: For quick-running flows where you need an immediate response. The API holds the connection open and returns the final result in a single request. Streaming is available for real-time progress updates.

  • Asynchronous Execution: For long-running tasks that might exceed standard timeout limits. The API immediately confirms the request and provides an ID to track the job's progress separately.

Managing API Keys

API keys are essential for authenticating your requests. All API calls must include your key in the X-API-Key header.

Viewing API Keys

  1. In the Studio page, click the "API Keys" button.

  2. A modal will open, displaying a list of your existing API keys.

  3. Each key shows its name and the actual key value.

Creating a New API Key

  1. Click the "API Keys" button, then select "New API Key" from the dropdown.

  2. In the Create API Key modal, enter a descriptive name for your new key.

  3. Click "Create API Key".

  4. The new key will be displayed. Copy it immediately, as you won't be able to see the full key again for security reasons.

Important: Store your API key securely. It won't be displayed again after you close the modal.

Deleting an API Key

  1. In the API Keys list, click the trash icon next to the key you want to delete.

  2. Confirm the deletion in the popup.

Note: Deleting an API key will immediately and permanently revoke access for any applications using that key.

API Endpoints

1. Simple Chatbots (OpenAI Compatible)

This endpoint provides a drop-in replacement for the OpenAI Chat Completions API, designed specifically for Simple Chatbots.

  • Endpoint: POST /v1/chat/completions

  • Purpose: Interact with a Simple Chatbot. Supports both streaming and non-streaming responses.

  • Headers:

    • X-API-Key: YOUR_API_KEY_HERE

    • Content-Type: application/json

  • Request Body:

    {
      "model": "YOUR_SIMPLE_CHATBOT_ID",
      "messages": [
        {
          "role": "user",
          "content": "Hello! Can you help me today?"
        }
      ],
      "stream": false
    }
    
  • Response Format:

    {
      "id": "chatcmpl-123",
      "object": "chat.completion",
      "created": 1677652288,
      "model": "YOUR_SIMPLE_CHATBOT_ID",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Of course! How can I assist you?"
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 10,
        "completion_tokens": 9,
        "total_tokens": 19
      }
    }
    

2. Synchronous Execution: Dream Builder (Chatflow)

Execute Chatflow

  • Endpoint: POST /execute_chatflow/{chatflow_id}/execute

  • Purpose: Execute a chatflow and receive the complete response.

  • Headers:

    • X-API-Key: YOUR_API_KEY_HERE

    • Content-Type: application/json

  • Request Body (Option 1: String Message):

    {
      "input_data": {
        "query": "Your message here",
        "custom_input": "..."
      }
    }
  • Request Body (Option 2: List of Messages):

    {
      "input_data": {
        "query": [
          {
            "role": "assistant",
            "content": "Initial message from the assistant"
          },
          {
            "role": "user",
            "content": "User message here"
          }
        ],
        "custom_input": "..."
      }
    }
  • Response Format:

    {
      "model": "chatflow_id",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Response content"
          }
        }
      ],
      "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "total_tokens": 0
      }
    }

Stream Execute Chatflow

  • Endpoint: POST /execute_chatflow/{chatflow_id}/stream_execute

  • Purpose: Execute a chatflow with real-time streaming updates (adequate for long-time execution flows).

  • Headers: Same as non-streaming endpoint.

  • Request Body: Same as non-streaming endpoint.

  • Response: A Server-Sent Events (SSE) stream with the following events:

    {
      "type": "execution_started",
      "timestamp": "2025-02-11T14:34:08.678088"
    }
    
    {
      "type": "node_started",
      "node_id": "inputNodeType-19d7",
      "node_label": "Input",
      "node_type": "inputNodeType",
      "timestamp": "2025-02-11T14:34:08.681607"
    }
    
    {
      "type": "node_completed",
      "node_id": "inputNodeType-19d7",
      "node_label": "Input",
      "node_type": "inputNodeType",
      "timestamp": "2025-02-11T14:34:08.687736"
    }
    
    {
      "type": "execution_completed",
      "final_output": {
        "query": "Hello.",
        "response": "Response content"
      }
    }

3. Synchronous Execution: Workflow Builder

Execute Workflow

  • Endpoint: POST /execute_workflow/{workflow_id}/execute

  • Purpose: Execute a workflow and receive the complete response.

  • Request Body: The request body format is the same as the Chatflow execute endpoint.

  • Response: A detailed JSON object containing the workflow execution results.

Stream Execute Workflow

  • Endpoint: POST /execute_workflow/{workflow_id}/stream_execute

  • Purpose: Execute a workflow with streaming updates.

  • Response: An SSE stream with execution updates, similar to the Chatflow streaming endpoint.

4. Asynchronous Execution (For Long-Running Tasks)

Pro Tip: For complex flows that may take a long time to complete, always use the asynchronous endpoints to avoid client-side timeouts.

  • Start Execution: POST /v1/executions/{chatbot_id}/async

  • Get Status: GET /v1/executions/{execution_id}

  • Stream Progress: GET /v1/executions/{execution_id}/stream

  • Cancel Execution: DELETE /v1/executions/{execution_id}

Content Types and Message Handling

Text Messages

For simple text messages, use a string directly:

{
  "role": "user",
  "content": "Hello, how can you help me today?"
}

Image Messages

For messages containing images, use the multimodal content format with base64-encoded images:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "What can you tell me about this image?"
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/jpeg;filename=photo.jpg;base64,/9j/4AAQSkZJRg..."
      }
    }
  ]
}

Mixed Content Messages

You can combine multiple content types in a single message:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "I found these two diagrams. Can you compare them?"
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/png;filename=diagram1.png;base64,iVBORw0KGgoAAAANSU..."
      }
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/png;filename=diagram2.png;base64,iVBORw0KGgoAAAANSU..."
      }
    }
  ]
}

File Handling

Text Files (PDF, PPTX, etc.)

Upload text files using base64-encoded data with metadata: data:[MIME type];filename=[filename];base64,[encoded content]

Examples:

# For PDF files
data:application/pdf;filename=document.pdf;base64,JVBERi0xLjcKCjEgMCBvYmo...

# For PPTX
data:application/vnd.openxmlformats-officedocument.presentationml.presentation;filename=document.pptx;base64,UEsDBBQABgA...

Image Files

Two options for image files:

  1. Base64-encoded data: data:image/jpeg;filename=photo.jpg;base64,/9j/4AAQSkZJRg...

  2. Direct URL:

    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.jpg"
      }
    }

Code Examples

Python

import requests
import base64

api_key = 'YOUR_API_KEY_HERE'
headers = {
    'X-API-Key': f'{api_key}',
    'Content-Type': 'application/json'
}

# Regular execution
data = {
    'input_data': {
      'query': 'Hello, how are you?'
    }
}
response = requests.post(
    'https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/execute',
    json=data,
    headers=headers
)
print(response.json()['choices'][0]['message']['content'])

# Streaming execution
def handle_stream():
    response = requests.post(
        'https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/stream_execute',
        json=data,
        headers=headers,
        stream=True
    )
    for line in response.iter_lines():
        if line:
            print(line.decode('utf-8'))

# File handling
def convert_file_to_base64(file_path):
    with open(file_path, 'rb') as file:
        return base64.b64encode(file.read()).decode('utf-8')

JavaScript

// Regular execution
const response = await fetch('https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/execute', {
  method: 'POST',
  headers: {
    'X-API-Key': 'YOUR_API_KEY_HERE',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    input_data: { query: 'Hello, how are you?' }
  })
});
const data = await response.json();
console.log(data.choices[0].message.content);

// Streaming execution (Conceptual for browser, requires backend proxy)
const eventSource = new EventSource('https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/stream_execute'
  // Note: Standard EventSource does not support custom headers or POST.
);
eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data);
};

// File handling helper
const convertFileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === 'string') {
        if (file.type.startsWith('image/')) {
          resolve(`data:${file.type};base64,${reader.result.split(',')[1]}`);
        } else {
          resolve(`data:${file.type};filename=${file.name};base64,${reader.result.split(',')[1]}`);
        }
      } else {
        reject(new Error('Failed to convert file to base64'));
      }
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

Best Practices

  • Security: Store API keys securely and never expose them in client-side code. Regularly rotate API keys.

  • Performance: Use streaming endpoints for real-time updates and asynchronous endpoints for long-duration flows to avoid timeout errors.

  • Error Handling: Implement proper timeout handling and retry logic for transient network errors.

Troubleshooting

  • Authentication Errors: Verify API key is valid and active. Check X-API-Key header format.

  • Request Format Errors: Validate JSON structure. Ensure required fields are present.

  • File Upload Issues: Check file format support. Ensure proper base64 encoding.

Last updated