API Integration Guide

âš ī¸ Plan Requirement
Direct API integration requires Starter plan or higher. Custom UI development requires Professional plan or higher.

View plan features →

Build custom chat experiences using the dialektai API directly. This guide covers direct API usage without the pre-built widget interface.

💡 Looking for Chat History?
For conversation management, message history, and pagination, see the Chat History Integration Guide.

When to Use API Integration

Choose API integration over widget integration if you need to:

Widget vs API Integration

Feature Widget Integration API Integration
Plan Required All plans (including free trial) Starter+ (basic)
Professional+ (custom UI)
API Key Type Database keys (pk_*) Organization keys (sk_*)
Use Case Quick embed, standard UI Custom implementations
UI Control Pre-built components Full customization
Integration Effort Minimal (3 lines of code) Custom development required
Client-Side Safe ✅ Yes (CORS protected) âš ī¸ Server-side recommended
Suitable For Web applications Web, mobile, backend services
💡 Looking for Widget Integration?
For quick embed with pre-built UI, see the Widget Integration Guide (available on all plans).

Prerequisites

Before you begin, you'll need:

  1. dialektai organization account with Starter plan or higher
  2. Connected database with completed schema indexing
  3. Organization API key (available in Settings → API Keys)
â„šī¸ Feature: `api_access` (Starter+)
Organization API keys are gated by the api_access feature:
- Starter, Professional, Business, Enterprise: ✅ Available
- Free Trial: ❌ Not available (upgrade required)

Authentication

Organization API Keys

Organization API keys (sk_*) provide broader access than database keys and are used for custom integrations.

Creating an Organization API Key

  1. Log in to your dialektai dashboard
  2. Navigate to Settings → API Keys
  3. Click Create Organization API Key
  4. Give it a descriptive name (e.g., "Mobile App", "Backend Service")
  5. Copy the generated key starting with sk_
  6. Store securely - you won't see it again!
âš ī¸ Security Note
Organization API keys have broader permissions than database keys. Never expose them in client-side code or public repositories.

Safe Usage:
- ✅ Server-side API calls
- ✅ Mobile apps with secure storage
- ✅ Backend services

Unsafe Usage:
- ❌ Embedded in web pages
- ❌ Committed to version control
- ❌ Client-side JavaScript

Authentication Methods

The dialektai API supports three authentication methods:

Method Header Use Case Plan Required
Organization API Key X-API-Key: sk_* Custom integrations Starter+
Database API Key X-API-Key: pk_* Widget/single database All plans
JWT Token Authorization: Bearer <token> Portal users N/A

For API integration, use Organization API Keys (sk_*).

Chat API Endpoints

Send Chat Message

Send a natural language query to your database and receive an AI-generated response.

Endpoint: POST /api/v1/chat/message

Headers:

X-API-Key: sk_your_organization_key_here
Content-Type: application/json
X-Tenant-Id: 82                    (optional, for multi-tenant filtering)
X-Scope-Id: user-123               (optional, for additional context)

Request Body:

{
  "message": "Show me top 10 customers by revenue",
  "database_id": "550e8400-e29b-41d4-a716-446655440000",
  "personality_id": "uuid-optional",
  "session_id": "uuid-optional"
}

Parameters:

Parameter Type Required Description
message string Yes Natural language query
database_id string (UUID) Yes Database to query against
personality_id string (UUID) No AI personality to use
session_id string (UUID) No Session for conversation continuity

Response:

{
  "success": true,
  "data": {
    "message": "Here are the top 10 customers by revenue...",
    "session_id": "550e8400-e29b-41d4-a716-446655440001",
    "results": [
      {
        "customer_name": "Acme Corp",
        "total_revenue": 150000
      }
      // ... more results
    ]
  }
}

Example: Basic cURL Request

curl -X POST https://api.dialektai.com/api/v1/chat/message \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Show me sales trends for the last 6 months",
    "database_id": "550e8400-e29b-41d4-a716-446655440000"
  }'

Example: Python Request

import requests
import os

# Securely load API key from environment
API_KEY = os.environ.get("DIALEKTAI_API_KEY")
DATABASE_ID = os.environ.get("DIALEKTAI_DATABASE_ID")

def query_database(message: str):
    response = requests.post(
        "https://api.dialektai.com/api/v1/chat/message",
        headers={
            "X-API-Key": API_KEY,
            "Content-Type": "application/json"
        },
        json={
            "message": message,
            "database_id": DATABASE_ID
        }
    )

    if response.status_code == 200:
        data = response.json()
        return data["data"]
    else:
        raise Exception(f"API Error: {response.status_code} - {response.text}")

# Usage
result = query_database("Show me top customers")
print(result["message"])
print(result["results"])

Example: Node.js/TypeScript Request

import axios from 'axios';

const API_KEY = process.env.DIALEKTAI_API_KEY!;
const DATABASE_ID = process.env.DIALEKTAI_DATABASE_ID!;

interface ChatResponse {
  success: boolean;
  data: {
    message: string;
    session_id: string;
    results: any[];
  };
}

async function queryDatabase(message: string): Promise<ChatResponse> {
  const response = await axios.post<ChatResponse>(
    'https://api.dialektai.com/api/v1/chat/message',
    {
      message,
      database_id: DATABASE_ID,
    },
    {
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json',
      },
    }
  );

  return response.data;
}

// Usage
const result = await queryDatabase('Show me top customers');
console.log(result.data.message);
console.log(result.data.results);

Multi-Tenant Data Filtering

For applications serving multiple customers, use tenant filtering to ensure users only see their own data.

How It Works

  1. Configure Database: Set requires_organization_scoping = true on your database connection
  2. Specify Tenant Column: Configure which column contains tenant IDs (e.g., customer_id, tenant_id, organization_id)
  3. Send Tenant ID: Include X-Tenant-Id header in API requests
  4. Automatic Filtering: All SQL queries automatically include WHERE tenant_column = tenant_id

Example with Tenant Filtering

curl -X POST https://api.dialektai.com/api/v1/chat/message \
  -H "X-API-Key: sk_your_key_here" \
  -H "X-Tenant-Id: 82" \
  -H "X-Scope-Id: user-456" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Show my orders from last month",
    "database_id": "your-db-uuid"
  }'

Headers Explanation:

Header Required Format Description
X-Tenant-Id Conditional* Positive integer Organization/customer ID for row-level filtering
X-Scope-Id Optional String or number User/department/role ID for additional filtering

*Required if database has requires_organization_scoping = true

âš ī¸ Tenant ID Validation
- Accepts any string format (integers: "82", UUIDs, custom strings: "customer-123")
- Validation is strict when requires_organization_scoping = true
- Invalid tenant IDs return 403 Forbidden
- Database must have tenant column configured

Python Example with Tenant Filtering

def query_for_customer(message: str, customer_id: str, user_id: str):
    """Query database with tenant filtering for specific customer."""
    response = requests.post(
        "https://api.dialektai.com/api/v1/chat/message",
        headers={
            "X-API-Key": API_KEY,
            "X-Tenant-Id": customer_id,        # Organization ID (any string format: "82", "customer-123", UUID)
            "X-Scope-Id": user_id,             # User ID (for tracking/additional filtering)
            "Content-Type": "application/json"
        },
        json={
            "message": message,
            "database_id": DATABASE_ID
        }
    )
    return response.json()

# Usage
result = query_for_customer(
    message="Show my sales this quarter",
    customer_id=82,  # Customer's organization ID
    user_id="user-456"  # Specific user making the request
)

Session Management

Sessions enable conversation continuity, allowing the AI to remember context from previous messages.

â„šī¸ Advanced Session Features
For conversation history, message retrieval, pagination, and session deletion, see the Chat History Integration Guide.

Creating a Session

Endpoint: POST /api/v1/chat/sessions

curl -X POST https://api.dialektai.com/api/v1/chat/sessions \
  -H "X-API-Key: sk_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "database_id": "your-db-uuid",
    "name": "Customer Analysis Session"
  }'

Response:

{
  "success": true,
  "data": {
    "session_id": "550e8400-e29b-41d4-a716-446655440002",
    "database_id": "550e8400-e29b-41d4-a716-446655440000",
    "name": "Customer Analysis Session",
    "created_at": "2025-01-15T10:30:00Z"
  }
}

Using Sessions in Chat

Include the session_id in subsequent messages:

{
  "message": "Now show me their purchase history",
  "database_id": "550e8400-e29b-41d4-a716-446655440000",
  "session_id": "550e8400-e29b-41d4-a716-446655440002"
}

The AI will maintain context from previous messages in the session.

Streaming Responses

For real-time response streaming (server-sent events):

Endpoint: GET /api/v1/chat/{session_id}/stream

const eventSource = new EventSource(
  `https://api.dialektai.com/api/v1/chat/${sessionId}/stream`,
  {
    headers: {
      'X-API-Key': API_KEY
    }
  }
);

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Streaming chunk:', data.content);
};

eventSource.onerror = (error) => {
  console.error('Stream error:', error);
  eventSource.close();
};

AI Personalities

Customize the AI's response style using personalities.

Getting Your Personality ID

Instead of making API calls, get your personality ID directly from the portal:

  1. Log in to the dialektai portal
  2. Navigate to Settings → AI Personalities
  3. Each personality card displays:
    • Name: Analytics Expert, Customer Support Bot, etc.
    • Response Style: CASUAL, PROFESSIONAL, TECHNICAL, etc.
    • Personality ID: UUID (e.g., a1201dbc-0d37-4c74-8ea0-235f7466162b)
  4. Click the Copy button next to the Personality ID
  5. Use that ID in your API requests
💡 Creating Custom Personalities
You can create custom personalities with:
- Custom system prompts and instructions
- Specific response styles (formal, friendly, technical, etc.)
- Custom greeting messages
- Enable/disable links and QA features

Go to Settings → AI Personalities → Create Personality

Use Personality in Chat

Include the personality_id in your API requests:

{
  "message": "Analyze Q4 performance",
  "database_id": "your-db-uuid",
  "personality_id": "a1201dbc-0d37-4c74-8ea0-235f7466162b"
}

Example with cURL:

curl -X POST https://api.dialektai.com/api/v1/chat/message \
  -H "X-API-Key: sk_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Show me top customers",
    "database_id": "550e8400-e29b-41d4-a716-446655440000",
    "personality_id": "a1201dbc-0d37-4c74-8ea0-235f7466162b"
  }'

Error Handling

Standard Error Response

{
  "success": false,
  "error": {
    "code": "INVALID_TENANT_ID",
    "message": "Invalid X-Tenant-Id header format. Must be a non-empty string.",
    "details": "Received value: ''"
  }
}

Common Error Codes

Status Code Error Code Description Solution
401 UNAUTHORIZED Invalid API key Check API key is correct
403 FORBIDDEN Missing required plan Upgrade to Starter+ plan
403 INVALID_TENANT_ID Tenant validation failed Ensure tenant ID is non-empty string (max 255 chars)
404 DATABASE_NOT_FOUND Database doesn't exist Verify database ID
429 RATE_LIMIT_EXCEEDED Too many requests Implement rate limiting
500 INTERNAL_SERVER_ERROR Server error Contact support

Error Handling Example

try:
    result = query_database("Show sales data")
except requests.exceptions.HTTPError as e:
    if e.response.status_code == 403:
        error = e.response.json()
        if error.get("error", {}).get("code") == "PLAN_FEATURE_REQUIRED":
            print("Upgrade required: API access needs Starter plan or higher")
        elif error.get("error", {}).get("code") == "INVALID_TENANT_ID":
            print("Invalid tenant ID format - must be non-empty string (max 255 chars)")
    elif e.response.status_code == 429:
        print("Rate limit exceeded - please slow down requests")
    else:
        print(f"API Error: {e.response.status_code}")

Rate Limiting

API requests are rate-limited based on your subscription plan to ensure fair usage and system stability.

For detailed information about rate limits, handling strategies, and best practices, see the Rate Limiting Guide.

Security Best Practices

When integrating with the dialektai API, follow security best practices to protect your API keys and data.

For comprehensive security guidelines including key management, rotation schedules, and secure storage, see the API Keys Guide.

Key Points for API Integration:

Building Custom Chat UIs

â„šī¸ Professional Plan Required
Building custom chat user interfaces requires the Professional plan or higher (custom_api_access feature).

To build a custom chat UI:

  1. Authenticate with organization API key (sk_*)
  2. Create session via /api/v1/chat/sessions
  3. Send messages via /api/v1/chat/message with session_id
  4. Display results in your custom UI components
  5. Handle streaming via /api/v1/chat/{session_id}/stream (optional)

Apply Organization Branding (Optional)

To maintain visual consistency with your organization's widget branding, custom UIs can fetch branding configuration:

Endpoint: GET /api/v1/branding

Example Request:

curl -X GET https://api.dialektai.com/api/v1/branding \
  -H "X-API-Key: sk_your_key_here"

Response:

{
  "success": true,
  "data": {
    "colors": {
      "primary": "#3b82f6",
      "secondary": "#8b5cf6",
      "accent": "#10b981",
      "text_primary": "#1f2937",
      "text_secondary": "#6b7280"
    },
    "logo_url": "https://assets.dialektai.com/orgs/123/logo.png",
    "logo_dark_url": "https://assets.dialektai.com/orgs/123/logo-dark.png",
    "widget_theme": {
      "position": "bottom-right",
      "greeting_message": "Hello! How can I help you?",
      "placeholder_text": "Ask a question...",
      "header_color": "#3b82f6"
    },
    "hide_dialektai_branding": false
  }
}

Use Case: Apply these colors and logos in your custom chat UI to match the appearance of the dialektai widget.

💡 Branding Configuration
Branding is configured in the portal at Settings → Branding. See the Branding Configuration Guide for setup instructions.

Migration from Widget to API

If you're currently using the widget and want to migrate to direct API:

  1. Upgrade plan to Starter or higher
  2. Create organization API key in dashboard
  3. Replace widget with your custom UI
  4. Call chat API from your backend (recommended) or secure client
  5. Implement authentication and tenant filtering
  6. Test thoroughly before removing widget

Next Steps