API Documentation

API Reference

Complete documentation for the N8.Chat REST API and JavaScript SDK. Build custom integrations and extend functionality.

REST API Overview

The N8.Chat API allows you to programmatically interact with the chat widget, send messages, and retrieve conversation data.

Base URL

https://api.n8chat.io/v1

All API requests should be made to this base URL. The API uses HTTPS exclusively.

RESTful Design

Standard HTTP methods and status codes

JSON Format

All requests and responses use JSON

Secure

API key authentication required

Authentication

All API requests require authentication using an API key. Include your API key in the request headers.

API Key Header

X-API-Key: your_api_key_here

Bearer Token (Alternative)

Authorization: Bearer your_api_key_here

Security: Never expose your API key in client-side code. Use server-side requests or environment variables.

Endpoints

POST/message

Send a message to the chat and receive an AI response. This is the primary endpoint for chat interactions.

Request Body

{
  "message": "What's your return policy?",
  "session_id": "sess_abc123",
  "context": {
    "page_url": "https://example.com/products/shoes",
    "page_title": "Running Shoes",
    "user_name": "John Doe",
    "cart_total": "$129.99"
  }
}
ParameterTypeRequiredDescription
messagestringYesThe user message to send
session_idstringNoSession ID for conversation continuity
contextobjectNoAdditional context data (page, user, cart)

Response

{
  "success": true,
  "message": "Our return policy allows returns within 30 days of purchase...",
  "session_id": "sess_abc123",
  "metadata": {
    "model": "gpt-4o-mini",
    "tokens_used": 150,
    "response_time_ms": 1250
  }
}
GET/conversation/{session_id}

Retrieve the full conversation history for a specific session.

Path Parameters

ParameterTypeDescription
session_idstringThe session ID to retrieve

Response

{
  "success": true,
  "session_id": "sess_abc123",
  "created_at": "2025-01-15T10:00:00Z",
  "updated_at": "2025-01-15T10:30:00Z",
  "messages": [
    {
      "id": "msg_001",
      "role": "user",
      "content": "What's your return policy?",
      "timestamp": "2025-01-15T10:25:00Z"
    },
    {
      "id": "msg_002",
      "role": "assistant",
      "content": "Our return policy allows returns within 30 days...",
      "timestamp": "2025-01-15T10:25:02Z"
    }
  ]
}
DELETE/conversation/{session_id}

Delete a conversation and all its messages. This action is irreversible.

Response

{
  "success": true,
  "message": "Conversation deleted successfully"
}
GET/sessions

List all chat sessions with pagination. Useful for analytics and admin dashboards.

Query Parameters

ParameterTypeDefaultDescription
pageinteger1Page number
per_pageinteger20Results per page (max 100)
fromstring-Start date (ISO 8601)
tostring-End date (ISO 8601)

Response

{
  "success": true,
  "data": [
    {
      "session_id": "sess_abc123",
      "created_at": "2025-01-15T10:00:00Z",
      "message_count": 5,
      "last_message_at": "2025-01-15T10:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "per_page": 20,
    "total": 150,
    "total_pages": 8
  }
}
POST/webhook/test

Test your webhook configuration by sending a test payload to your n8n endpoint.

Request Body

{
  "webhook_url": "https://your-n8n.com/webhook/chat",
  "test_message": "This is a test message"
}

Response

{
  "success": true,
  "webhook_response": {
    "status": 200,
    "body": { "message": "Response from n8n" },
    "response_time_ms": 850
  }
}

Error Codes

The API uses standard HTTP status codes and returns detailed error messages.

CodeNameDescription
200OKRequest successful
201CreatedResource created successfully
400Bad RequestInvalid request body or parameters
401UnauthorizedMissing or invalid API key
403ForbiddenAPI key lacks required permissions
404Not FoundResource not found
429Too Many RequestsRate limit exceeded
500Server ErrorInternal server error
502Bad GatewayWebhook endpoint unreachable

Error Response Format

{
  "success": false,
  "error": {
    "code": "INVALID_REQUEST",
    "message": "The 'message' field is required",
    "details": {
      "field": "message",
      "reason": "missing_required_field"
    }
  }
}

Rate Limits

To ensure fair usage and system stability, API requests are rate limited.

PlanRequests/MinuteRequests/DayBurst Limit
Free601,00010
Pro30010,00050
Enterprise1,000Unlimited200

Rate Limit Headers

Rate limit information is included in response headers:

X-RateLimit-Limit: 300
X-RateLimit-Remaining: 295
X-RateLimit-Reset: 1705312260

Code Examples

JavaScript / Node.js

// Using fetch
const response = await fetch('https://api.n8chat.io/v1/message', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your_api_key_here'
  },
  body: JSON.stringify({
    message: 'What is your return policy?',
    session_id: 'sess_abc123',
    context: {
      page_url: window.location.href,
      user_name: 'John Doe'
    }
  })
});

const data = await response.json();
console.log(data.message);

Python

import requests

response = requests.post(
    'https://api.n8chat.io/v1/message',
    headers={
        'Content-Type': 'application/json',
        'X-API-Key': 'your_api_key_here'
    },
    json={
        'message': 'What is your return policy?',
        'session_id': 'sess_abc123',
        'context': {
            'page_url': 'https://example.com',
            'user_name': 'John Doe'
        }
    }
)

data = response.json()
print(data['message'])

cURL

curl -X POST https://api.n8chat.io/v1/message \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your_api_key_here" \
  -d '{
    "message": "What is your return policy?",
    "session_id": "sess_abc123",
    "context": {
      "page_url": "https://example.com",
      "user_name": "John Doe"
    }
  }'

PHP

<?php
$ch = curl_init('https://api.n8chat.io/v1/message');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-API-Key: your_api_key_here'
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'message' => 'What is your return policy?',
        'session_id' => 'sess_abc123',
        'context' => [
            'page_url' => 'https://example.com',
            'user_name' => 'John Doe'
        ]
    ])
]);

$response = curl_exec($ch);
$data = json_decode($response, true);
echo $data['message'];

JavaScript SDK

The N8.Chat widget exposes a JavaScript API for programmatic control.

Available Methods

window.N8Chat.open()

Opens the chat widget

window.N8Chat.close()

Closes the chat widget

window.N8Chat.toggle()

Toggles the chat widget open/closed

window.N8Chat.sendMessage(text)

Sends a message programmatically

window.N8Chat.setContext(data)

Sets custom context data

window.N8Chat.getContext()

Returns current context data

window.N8Chat.clearHistory()

Clears conversation history

window.N8Chat.on(event, callback)

Subscribe to widget events

Events

EventDescription
openFired when chat widget opens
closeFired when chat widget closes
message:sentFired when user sends a message
message:receivedFired when AI response is received
errorFired when an error occurs

Example Usage

// Open chat when a button is clicked
document.getElementById('help-button').addEventListener('click', () => {
  window.N8Chat.open();
});

// Set custom context
window.N8Chat.setContext({
  subscription_tier: 'premium',
  account_age_days: 365,
  preferred_language: 'en'
});

// Listen for messages
window.N8Chat.on('message:received', (message) => {
  console.log('AI responded:', message.content);

  // Track in analytics
  analytics.track('chat_response', {
    session_id: message.session_id,
    response_time: message.response_time_ms
  });
});

// Send a proactive message
if (cart.total > 100 && !cart.hasFreeShipping) {
  window.N8Chat.open();
  window.N8Chat.sendMessage('I see you have items in your cart!');
}