REST API Endpoints

This document covers REST endpoints outside of the tRPC framework, including the External REST API (/api/v1), file uploads, widget embeds, and webhooks.


External REST API

Use the External REST API for programmatic access to tickets, customers, conversations, and other core resources.

Base URL: https://your-domain.com/api/v1

Authentication: Authorization: Bearer YOUR_API_KEY

OpenAPI spec: https://your-domain.com/openapi.json

For the full set of endpoints, see the OpenAPI spec or the knowledge base REST reference.


File Upload

Upload File

Upload a file attachment to be associated with tickets or conversations.

Endpoint: POST /api/upload

Authentication: Required (session cookie)

Content-Type: multipart/form-data

Request Body:

FieldTypeRequiredDescription
fileFileYesThe file to upload
conversationIdstringNoAssociate with a conversation
ticketIdstringNoAssociate with a ticket

Constraints:

  • Maximum file size: 10MB
  • All common file types accepted

Example:

curl -X POST "https://your-domain.com/api/upload" \
  -H "Cookie: your-session-cookie" \
  -F "file=@/path/to/document.pdf" \
  -F "conversationId=conversation-uuid"

Response:

{
  "id": "attachment-uuid",
  "filename": "document.pdf",
  "url": "https://storage.example.com/attachments/user-id/abc123.pdf",
  "size": 102400,
  "type": "application/pdf"
}

Error Responses:

  • 401 Unauthorized - Not authenticated
  • 400 Bad Request - No file provided
  • 400 Bad Request - File too large (>10MB)
  • 403 Forbidden - User not associated with organization

Attachment Download

Download Attachment

Get a signed URL to download an attachment.

Endpoint: GET /api/attachments/{id}/download

Authentication: Required (session cookie)

Path Parameters:

ParameterTypeDescription
idstringAttachment UUID

Example:

curl -X GET "https://your-domain.com/api/attachments/attachment-uuid/download" \
  -H "Cookie: your-session-cookie"

Response:

{
  "url": "https://storage.example.com/attachments/signed-url?token=xxx",
  "filename": "document.pdf",
  "mimeType": "application/pdf"
}

Notes:

  • Signed URL is valid for 1 hour
  • User must belong to the same organization as the attachment

Widget API

The Widget API allows external websites to embed a support widget. These endpoints use API key authentication via the widget configuration.

Initialize Widget Session

Create a new widget session for a visitor.

Endpoint: POST /api/widget/init

Authentication: Widget API key

Request Body:

{
  "apiKey": "widget-api-key",
  "visitorId": "optional-visitor-id",
  "metadata": {
    "page_url": "https://example.com/page",
    "referrer": "https://google.com"
  }
}

Response:

{
  "success": true,
  "sessionToken": "unique-session-token",
  "config": {
    "theme": {
      "primaryColor": "#007bff",
      "position": "bottom-right"
    },
    "preChatForm": [...],
    "allowFileUploads": true
  }
}

Get Widget Configuration

Retrieve widget theme and form configuration.

Endpoint: GET /api/widget/config?apiKey=xxx

Authentication: Widget API key (query param)

CORS: Enabled (cross-origin requests allowed)

Example:

curl -X GET "https://your-domain.com/api/widget/config?apiKey=widget-api-key"

Response:

{
  "success": true,
  "config": {
    "theme": {
      "primaryColor": "#007bff",
      "headerText": "How can we help?",
      "position": "bottom-right"
    },
    "formFields": [
      { "name": "name", "label": "Name", "type": "text", "required": true },
      { "name": "email", "label": "Email", "type": "email", "required": true }
    ]
  }
}

Send Widget Message

Send a message from the widget, creating or updating a ticket.

Endpoint: POST /api/widget/message

Authentication: Session token (from /api/widget/init)

Request Body:

{
  "sessionToken": "session-token-from-init",
  "message": "I need help with my order",
  "attachments": []
}

Response:

{
  "success": true,
  "ticketId": "ticket-uuid",
  "conversationId": "conversation-uuid"
}

Notes:

  • Creates a new ticket on first message
  • Subsequent messages add to existing ticket
  • Duplicate detection prevents double submissions (30 second window)
  • AI reply suggestions are generated automatically

Get Widget Messages

Retrieve message history for a widget session.

Endpoint: GET /api/widget/message?sessionToken=xxx

Authentication: Session token (query param)

Response:

{
  "messages": [
    {
      "id": "conversation-uuid",
      "content": { "type": "doc", "content": [...] },
      "content_text": "I need help with my order",
      "created_at": "2024-01-15T10:30:00.000Z",
      "author": {
        "name": "John Smith",
        "avatar_url": null,
        "role": "agent"
      }
    }
  ]
}

Submit Contact Form

Submit a contact form without requiring a session. Creates a ticket directly.

Endpoint: POST /api/widget/contact

Authentication: Widget API key

CORS: Enabled (cross-origin requests allowed)

Request Body:

{
  "apiKey": "widget-api-key",
  "name": "John Doe",
  "email": "john@example.com",
  "message": "I have a question about your product",
  "customFields": {
    "company": "Acme Corp",
    "phone": "+1-555-0123"
  }
}

Response:

{
  "success": true,
  "ticketId": "ticket-uuid",
  "ticketNumber": 1234,
  "message": "Thank you for contacting us. We will get back to you soon."
}

Notes:

  • Domain whitelist is enforced if configured
  • Customer record is created/updated automatically
  • Geolocation is captured from IP address
  • AI reply suggestions generated for agents
  • Auto-translation for non-English messages

Health Check

Get System Health

Check system health status including database and Redis connectivity.

Endpoint: GET /api/health

Authentication: None required

Example:

curl -X GET "https://your-domain.com/api/health"

Response (Healthy):

{
  "status": "healthy",
  "version": "1.0.0",
  "uptime": 3600.5,
  "checks": {
    "database": {
      "status": "healthy",
      "latencyMs": 15
    },
    "redis": {
      "status": "healthy",
      "latencyMs": 5
    },
    "environment": {
      "status": "healthy"
    }
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Response (Degraded):

{
  "status": "degraded",
  "version": "1.0.0",
  "uptime": 3600.5,
  "checks": {
    "database": {
      "status": "degraded",
      "latencyMs": 2500,
      "detail": "Slow response time"
    },
    "redis": {
      "status": "not_configured"
    },
    "environment": {
      "status": "healthy"
    }
  },
  "timestamp": "2024-01-15T10:30:00.000Z"
}

Status Codes:

  • 200 OK - All checks healthy
  • 503 Service Unavailable - One or more checks failed

Health Check (HEAD)

Simple uptime check without full health details.

Endpoint: HEAD /api/health

Response: 200 OK (no body)


Webhooks

Webhook endpoints receive events from external services. All webhooks verify signatures before processing.

Stripe Webhooks

Receive payment and subscription events from Stripe.

Endpoint: POST /api/webhooks/stripe

Authentication: Stripe signature (stripe-signature header)

Handled Events:

EventDescription
setup_intent.succeededPayment method setup completed
setup_intent.setup_failedPayment method setup failed
payment_intent.succeededPayment charge succeeded
payment_intent.payment_failedPayment charge failed
payment_method.attachedPayment method added to customer
payment_method.detachedPayment method removed
checkout.session.completedCheckout flow completed
customer.subscription.createdSubscription created
customer.subscription.updatedSubscription updated
customer.subscription.deletedSubscription canceled
customer.subscription.trial_will_endTrial ending in 3 days
invoice.paidInvoice payment succeeded
invoice.payment_failedInvoice payment failed

Actions:

  • Updates subscription status in database
  • Stores payment methods and invoices
  • Sends email notifications (receipts, payment failures, trial ending)

Shopify Webhooks

Receive customer and order events from Shopify stores.

Endpoint: POST /api/webhooks/shopify

Authentication: Shopify HMAC signature (x-shopify-hmac-sha256 header)

Required Headers:

  • x-shopify-topic - Webhook topic
  • x-shopify-shop-domain - Shop domain
  • x-shopify-hmac-sha256 - HMAC signature

Handled Topics:

TopicDescription
customers/createNew customer created
customers/updateCustomer updated
orders/createNew order placed
orders/updatedOrder updated
orders/fulfilledOrder fully fulfilled
orders/partially_fulfilledOrder partially fulfilled

Actions:

  • Syncs customer data to CRM
  • Tracks orders in shopify_orders table
  • Can create support tickets for orders (optional)

Shopify GDPR Webhooks

Handle Shopify-required GDPR webhooks for app compliance.

Endpoint: POST /api/webhooks/shopify/gdpr

Authentication: Shopify HMAC signature (x-shopify-hmac-sha256 header)

Handled Topics:

TopicDescription
customers/data_requestCustomer data request
customers/redactCustomer data deletion
shop/redactShop data deletion

Notes:

  • Required by Shopify for app approval
  • Uses API secret for HMAC validation

Amazon SNS Webhooks

Receive Amazon Seller Central notifications via SNS.

Endpoint: POST /api/amazon/webhook

Authentication: Amazon SNS signature verification

Handled Notification Types (examples):

  • ORDER_CHANGE
  • MFN_ORDER_STATUS_CHANGE
  • RETURN_STATUS_CHANGE
  • FEED_PROCESSING_FINISHED

Notes:

  • Supports SNS subscription confirmation
  • Processes events for the Amazon integration

Email Webhooks (Resend)

Receive inbound emails from Resend.

Endpoints:

  • POST /api/webhooks/resend
  • POST /api/webhooks/email (legacy alias)

Authentication: Svix signature verification

Required Headers:

  • svix-signature - Webhook signature
  • svix-timestamp - Timestamp
  • svix-id - Event ID

Handled Events:

EventDescription
email.receivedInbound email received

Processing:

  1. Extract organization from recipient email format
  2. Filter outbound emails (from organization senders)
  3. Check if sender is blocked
  4. Create or update ticket based on thread ID
  5. Create conversation entry
  6. Process attachments

Email Threading:

  • Uses In-Reply-To and References headers
  • Falls back to subject matching for deduplication

Stripe Connect Webhooks

Receive events for connected Stripe accounts.

Endpoint: POST /api/webhooks/stripe-connect

Authentication: Stripe signature


SMS Webhooks

Receive inbound SMS messages.

Endpoint: POST /api/webhooks/sms


Slack Webhooks

Receive Slack app events.

Endpoint: POST /api/webhooks/slack


WhatsApp Webhooks

Receive WhatsApp message events.

Endpoint: POST /api/webhooks/whatsapp


Messenger Webhooks

Receive Facebook Messenger events.

Endpoint: POST /api/webhooks/messenger


Dialpad Webhooks

Receive Dialpad call events.

Endpoint: POST /api/webhooks/dialpad


Inbound Email (IMAP)

Process emails from IMAP sync.

Endpoint: POST /api/webhooks/inbound-email


OAuth Callbacks

OAuth callback endpoints complete the authentication flow for integrations.

IntegrationCallback URL
ShopifyGET /api/shopify/callback
WhatsAppGET /api/whatsapp/callback
MessengerGET /api/messenger/callback
AmazonGET /api/amazon/callback
ZendeskGET /api/zendesk/callback
Stripe ConnectGET /api/stripe-connect/callback

See Integrations API for the full OAuth flow.


Integration Install Endpoints

Start the OAuth flow for integrations.

IntegrationInstall URL
ShopifyGET /api/shopify/install?shop=store.myshopify.com&organization_id=org-uuid
WhatsAppGET /api/whatsapp/install?organization_id=org-uuid
MessengerGET /api/messenger/install?organization_id=org-uuid
AmazonGET /api/amazon/install?organization_id=org-uuid&marketplace=ATVPDKIKX0DER
Stripe ConnectGET /api/stripe-connect/install?organization_id=org-uuid
ZendeskGET /api/zendesk/connect?subdomain=your-subdomain&organization_id=org-uuid

Data Import Endpoints

Freshdesk Credential Validation

Validate Freshdesk credentials before starting an import.

Endpoint: POST /api/freshdesk/connect

Request Body:

{
  "domain": "company.freshdesk.com",
  "apiKey": "your-freshdesk-api-key"
}

Response:

{
  "success": true,
  "domain": "company.freshdesk.com",
  "message": "Freshdesk connection successful"
}

Zendesk Import

Start Import: POST /api/zendesk/import

Check Status: GET /api/zendesk/import/{importId}

Freshdesk Import

Start Import: POST /api/freshdesk/import

Check Status: GET /api/freshdesk/import/{importId}


Custom Integration Endpoints

Levy Fleets Ticket Intake

Receive tickets from the Levy Fleets backend.

Endpoint: POST /api/levy-fleets/tickets

Authentication: x-api-key header (LEVY_FLEETS_API_KEY)

Request Body (example):

{
  "email": "rider@example.com",
  "message": "Battery issue on ride",
  "subject": "Ride issue",
  "vehicle_number": "LF-1021",
  "image_url": "https://example.com/photo.jpg"
}

Notes:

  • Associates ticket with the Levy Fleets organization
  • Creates or updates the customer record automatically

Cron Jobs

IMAP Sync

Periodic sync for IMAP email accounts.

Endpoint: GET /api/cron/imap-sync

Notes:

  • Called by scheduled cron job
  • Syncs all configured IMAP integrations

Admin Endpoints

RAG Sync

Trigger knowledge base embedding sync for RAG.

Endpoint: POST /api/admin/rag-sync

Authentication: Admin required


AI Endpoints

Stream Reply Suggestions

Stream AI-generated reply suggestions.

Endpoint: POST /api/ai/stream-reply-suggestions

Authentication: Required

Notes:

  • Uses Server-Sent Events (SSE)
  • Streams tokens as they're generated

Diagnostics and Debug Endpoints

These endpoints are intended for internal debugging and setup verification.

Shopify Debug

Endpoint: GET /api/shopify/debug

Returns computed OAuth settings and which environment variables are present.

Shopify Debug Env

Endpoint: GET /api/shopify/debug-env

Returns raw environment configuration values (secrets are masked).

Shopify Status

Endpoint: GET /api/shopify/status

Returns deployment status and a quick configuration sanity check.

Shopify Verify

Endpoint: GET /api/shopify/verify

Runs Shopify config validation and returns warnings/errors.

Shopify Verify Secret

Endpoint: GET /api/shopify/verify-secret

Test endpoint for HMAC debugging with known Shopify examples.

Shopify Test OAuth URL

Endpoint: GET /api/shopify/test-oauth-url

Generates test OAuth URLs for debugging the Shopify install flow.