API Integration Guide
View plan features â
Build custom chat experiences using the dialektai API directly. This guide covers direct API usage without the pre-built widget interface.
When to Use API Integration
Choose API integration over widget integration if you need to:
- Build custom chat UIs with your own design and branding
- Integrate into mobile applications (iOS, Android, React Native, Flutter)
- Create backend-to-backend integrations for server-side query processing
- Use dialektai in non-web platforms or custom environments
- Full control over the user experience and interaction flow
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 |
Prerequisites
Before you begin, you'll need:
- dialektai organization account with Starter plan or higher
- Connected database with completed schema indexing
- Organization API key (available in Settings â API Keys)
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
- Log in to your dialektai dashboard
- Navigate to Settings â API Keys
- Click Create Organization API Key
- Give it a descriptive name (e.g., "Mobile App", "Backend Service")
- Copy the generated key starting with
sk_ - Store securely - you won't see it again!
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
- Configure Database: Set
requires_organization_scoping = trueon your database connection - Specify Tenant Column: Configure which column contains tenant IDs (e.g.,
customer_id,tenant_id,organization_id) - Send Tenant ID: Include
X-Tenant-Idheader in API requests - 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
"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.
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:
- Log in to the dialektai portal
- Navigate to Settings â AI Personalities
- 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)
- Click the Copy button next to the Personality ID
- Use that ID in your API requests
- 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:
- Never expose organization API keys (
sk_*) in client-side code - Use environment variables for storing API keys
- Implement proper tenant validation to prevent unauthorized data access
- Rotate keys regularly (every 90 days recommended)
- Monitor API usage and set up alerts for unusual activity
Building Custom Chat UIs
custom_api_access feature).To build a custom chat UI:
- Authenticate with organization API key (
sk_*) - Create session via
/api/v1/chat/sessions - Send messages via
/api/v1/chat/messagewithsession_id - Display results in your custom UI components
- 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.
Migration from Widget to API
If you're currently using the widget and want to migrate to direct API:
- Upgrade plan to Starter or higher
- Create organization API key in dashboard
- Replace widget with your custom UI
- Call chat API from your backend (recommended) or secure client
- Implement authentication and tenant filtering
- Test thoroughly before removing widget
Next Steps
- Chat History Integration Guide - Conversation management and history
- API Keys Guide - Authentication and key management
- Rate Limiting Guide - Rate limits and best practices
- Widget Integration Guide - Pre-built widget integration