SpecOS SpecOS icon Documentation

API Endpoints

This document provides details on the available API endpoints. For information on authentication, please see the API Keys documentation.

Available Endpoints

1. Chat AI - /api/chat-ai

Interact with SpecRight's AI chat system for product inquiries and technical questions.

Endpoint: POST /api/chat-ai

Headers:

Authorization: Bearer sk_your_api_key
Content-Type: application/json

Request Body:

{
	"message": "Tell me about LED lighting fixtures",
	"product": null,
	"sessionId": "optional-existing-session-id",
	"sessionToken": "optional-existing-session-token"
}

Parameters:

  • message (string, required): Your question or message
  • product (object, optional): Attached product data for context
  • sessionId (string, optional): Continue an existing conversation
  • sessionToken (string, optional): Session token for conversation continuity

Response:

{
	"message": {
		"id": "msg_123",
		"role": "assistant",
		"content": "LED lighting fixtures are...",
		"timestamp": 1703123456789,
		"metadata": {
			"debug": {
				"timing": { "total": 1234 },
				"toolsUsed": ["product_search"],
				"queryIntent": "product_inquiry"
			}
		}
	},
	"sessionId": "session_abc",
	"sessionToken": "token_xyz",
	"title": "LED Lighting Discussion",
	"activeProductIds": ["prod_1", "prod_2"],
	"timing": {
		"total": 1234,
		"auth": 45,
		"queryProcessing": 234,
		"toolExecution": 567,
		"responseGeneration": 388
	}
}

Postman Example:

// POST {{base_url}}/api/chat-ai
// Headers: Authorization: Bearer {{api_key}}
{
  "message": "What are the best LED strips for under-cabinet lighting?"
}

2. Vector Search - /api/vector-search

Search through SpecRight's product database using semantic vector search.

Endpoint: POST /api/vector-search

Headers:

Authorization: Bearer sk_your_api_key
Content-Type: application/json

Request Body:

{
	"query": "waterproof LED strip lights",
	"top_k": 10,
	"threshold": 0.75,
	"image": "base64-encoded-image-optional"
}

Parameters:

  • query (string, required if no image): Text search query
  • image (string, required if no query): Base64-encoded image for visual search
  • top_k (integer, optional, default 100): Maximum number of results
  • threshold (float, optional, default 0.75): Minimum similarity score (0.0-1.0)

Response:

{
	"results": [
		{
			"id": "product_123",
			"score": 0.89,
			"product_name": "Waterproof LED Strip - 5050",
			"brand": "Phillips",
			"sku": "LED-5050-WP",
			"category": "LED Lighting",
			"description": "IP65 rated waterproof LED strip...",
			"rrp": "$29.99"
		}
	],
	"query": "waterproof LED strip lights",
	"timestamp": "2024-03-15T10:30:00Z"
}

Postman Example:

// POST {{base_url}}/api/vector-search
// Headers: Authorization: Bearer {{api_key}}
{
  "query": "industrial grade ethernet switches",
  "top_k": 5,
  "threshold": 0.8
}

3. Chat Search - /api/chat-search

A multi-turn endpoint that uses natural language to search for products and returns a conversational response.

Endpoint: POST /api/chat-search

Headers:

Authorization: Bearer sk_your_api_key
Content-Type: application/json

Request Body:

{
	"message": "I'm looking for a stainless steel refrigerator with a water dispenser.",
	"sessionId": "optional-session-id",
	"messages": [
		{ "role": "user", "content": "Tell me about refrigerators" },
		{ "role": "assistant", "content": "We have many types. What features are you interested in?" }
	]
}

Parameters:

  • message (string, required): The user's natural language query.
  • sessionId (string, optional): An existing session ID to continue a conversation.
  • messages (array, optional): A history of previous messages in the conversation for context.

Response:

{
	"message": "I found several stainless steel refrigerators with water dispensers. I've listed them below.",
	"results": {
		"Refrigerator": [
			{
				"id": "prod_456",
				"product_name": "Stainless Steel French Door Refrigerator",
				"brand": "Samsung",
				"similarity": 0.92
			}
		]
	},
	"sessionId": "new-or-existing-session-id",
	"sessionToken": "a-new-session-token"
}

4. Analytics: Messages - /api/analytics/messages

Retrieve chat message data for analytics. This endpoint supports filtering by date range and message role.

Endpoint: GET /api/analytics/messages

Headers:

Authorization: Bearer sk_your_api_key

Query Parameters:

  • start_date (string, optional): Start date in YYYY-MM-DD format.
  • end_date (string, optional): End date in YYYY-MM-DD format.
  • role (string, optional): Filter by message role (e.g., user or assistant).
  • format (string, optional): json (default) or csv.

Response (JSON):

[
	{
		"session_id": "session_abc",
		"message_id": "msg_123",
		"created_at": "2024-03-15T10:30:00Z",
		"role": "user",
		"content": "Tell me about LED lighting"
	}
]

5. Analytics: Overview - /api/analytics/overview

Retrieve a daily summary of chat activity, including the number of sessions and total messages.

Endpoint: GET /api/analytics/overview

Headers:

Authorization: Bearer sk_your_api_key

Query Parameters:

  • start_date (string, optional): Start date in YYYY-MM-DD format.
  • end_date (string, optional): End date in YYYY-MM-DD format.
  • format (string, optional): json (default) or csv.

Response (JSON):

[
	{
		"day": "2024-03-15",
		"total_sessions": 50,
		"total_messages": 250,
		"avg_messages_per_session": 5
	}
]

Error Responses

401 Unauthorized

{
	"error": "Invalid or inactive API key."
}

429 Too Many Requests

{
	"error": "API usage limit exceeded. Please upgrade your plan or wait for the monthly reset."
}

Headers:

  • X-RateLimit-Limit: Your usage limit per month
  • X-RateLimit-Remaining: Remaining requests this month
  • Retry-After: Seconds until limit resets (monthly)

400 Bad Request

{
	"error": "Search query or image is required"
}

500 Internal Server Error

{
	"error": "An unexpected error occurred during search: [details]"
}

Rate Limiting

Rate limiting headers are included in responses when approaching or exceeding limits:

  • X-RateLimit-Limit: Maximum requests allowed per month
  • X-RateLimit-Remaining: Number of requests remaining in current month
  • Retry-After: Time in seconds until the rate limit window resets

Postman Collection

Environment Variables

Create a Postman environment with these variables:

  • base_url: https://your-specright-domain.com
  • api_key: sk_your32characterhexkey

Example Collection Structure

SpecRight API/
├── Chat AI/
│   ├── Basic Chat Query
│   ├── Product Inquiry
│   └── Continue Conversation
└── Vector Search/
    ├── Text Search
    ├── Image Search
    └── High Precision Search

Pre-request Script (Collection Level)

// Add timestamp to requests
pm.globals.set('timestamp', new Date().toISOString());

// Validate API key format
const apiKey = pm.environment.get('api_key');
if (!apiKey || !apiKey.startsWith('sk_')) {
	throw new Error("API key must start with 'sk_'");
}

Test Scripts

// Common test for all endpoints
pm.test('Status code should be 200 or expected error', function () {
	pm.expect([200, 401, 429, 400, 500]).to.include(pm.response.code);
});

pm.test('Response has correct content type', function () {
	pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json');
});

// Check rate limiting headers
pm.test('Rate limiting headers present', function () {
	if (pm.response.code === 429) {
		pm.expect(pm.response.headers.has('X-RateLimit-Limit')).to.be.true;
		pm.expect(pm.response.headers.has('X-RateLimit-Remaining')).to.be.true;
		pm.expect(pm.response.headers.has('Retry-After')).to.be.true;
	}
});

Code Examples

Node.js/JavaScript

const fetch = require('node-fetch');

async function searchProducts(query) {
	const response = await fetch('https://your-domain.com/api/vector-search', {
		method: 'POST',
		headers: {
			Authorization: 'Bearer sk_your_api_key',
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({
			query: query,
			top_k: 10
		})
	});

	if (!response.ok) {
		throw new Error(`API Error: ${response.status} ${response.statusText}`);
	}

	return response.json();
}

searchProducts('LED lighting').then(console.log);

Python

import requests

def chat_with_ai(message, api_key):
    url = 'https://your-domain.com/api/chat-ai'
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }
    payload = {
        'message': message
    }

    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    return response.json()

result = chat_with_ai("What are the specifications for industrial switches?", "sk_your_api_key")
print(result['message']['content'])

cURL

# Chat AI
curl -X POST "https://your-domain.com/api/chat-ai" \
  -H "Authorization: Bearer sk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"message": "Tell me about LED fixtures"}'

# Vector Search
curl -X POST "https://your-domain.com/api/vector-search" \
  -H "Authorization: Bearer sk_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"query": "waterproof connectors", "top_k": 5}'

Best Practices

  1. Store API keys securely - Never commit them to code repositories
  2. Handle rate limits gracefully - Check headers and implement exponential backoff
  3. Use appropriate top_k values - Smaller values are faster and use less quota
  4. Cache responses when possible - Reduce API calls for repeated queries
  5. Monitor your usage - Check your usage in the SpecRight dashboard
  6. Use session tokens - For chat conversations, maintain session continuity