# API Documentation

### Overview <a href="#overview" id="overview"></a>

AINexLayer provides a RESTful API for programmatic access to all platform features. The API supports authentication, workspace management, document processing, chat interactions, and more.

### Base URL <a href="#base-url" id="base-url"></a>

```
Production: https://api.ainexlayer.com/api/v1
Development: http://localhost:3001/api/v1
```

### Authentication <a href="#authentication" id="authentication"></a>

#### API Key Authentication <a href="#api-key-authentication" id="api-key-authentication"></a>

```bash
# Include API key in header
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.ainexlayer.com/api/v1/workspaces
```

#### JWT Token Authentication <a href="#jwt-token-authentication" id="jwt-token-authentication"></a>

```bash
# Login to get JWT token
curl -X POST https://api.ainexlayer.com/api/v1/auth/login \
     -H "Content-Type: application/json" \
     -d '{"email": "user@example.com", "password": "password"}'

# Use JWT token in subsequent requests
curl -H "Authorization: Bearer JWT_TOKEN" \
     https://api.ainexlayer.com/api/v1/workspaces
```

### Common Response Formats <a href="#common-response-formats" id="common-response-formats"></a>

#### Success Response <a href="#success-response" id="success-response"></a>

```json
{
  "success": true,
  "data": {
    "id": "workspace-123",
    "name": "My Workspace",
    "createdAt": "2024-01-15T10:30:00Z"
  },
  "message": "Operation completed successfully"
}
```

#### Error Response <a href="#error-response" id="error-response"></a>

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input parameters",
    "details": {
      "field": "name",
      "reason": "Name is required"
    }
  }
}
```

#### Paginated Response <a href="#paginated-response" id="paginated-response"></a>

```json
{
  "success": true,
  "data": [
    {
      "id": "item-1",
      "name": "Item 1"
    },
    {
      "id": "item-2",
      "name": "Item 2"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100,
    "totalPages": 5,
    "hasNext": true,
    "hasPrev": false
  }
}
```

### Authentication Endpoints <a href="#authentication-endpoints" id="authentication-endpoints"></a>

#### Login <a href="#login" id="login"></a>

```http
POST /auth/login
```

**Request Body:**

```json
{
  "email": "user@example.com",
  "password": "password"
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": "user-123",
      "email": "user@example.com",
      "name": "John Doe",
      "role": "user"
    },
    "expiresIn": 3600
  }
}
```

#### Register <a href="#register" id="register"></a>

```http
POST /auth/register
```

**Request Body:**

```json
{
  "email": "user@example.com",
  "password": "password",
  "firstName": "John",
  "lastName": "Doe"
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "user-123",
    "email": "user@example.com",
    "name": "John Doe",
    "role": "user",
    "emailVerified": false
  },
  "message": "User registered successfully. Please verify your email."
}
```

#### Refresh Token <a href="#refresh-token" id="refresh-token"></a>

```http
POST /auth/refresh
```

**Request Body:**

```json
{
  "refreshToken": "refresh_token_here"
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "token": "new_jwt_token",
    "expiresIn": 3600
  }
}
```

#### Logout <a href="#logout" id="logout"></a>

```http
POST /auth/logout
```

**Headers:**

```
Authorization: Bearer JWT_TOKEN
```

**Response:**

```json
{
  "success": true,
  "message": "Logged out successfully"
}
```

### Workspace Endpoints <a href="#workspace-endpoints" id="workspace-endpoints"></a>

#### List Workspaces <a href="#list-workspaces" id="list-workspaces"></a>

```http
GET /workspaces
```

**Query Parameters:**

* `page` (optional): Page number (default: 1)
* `limit` (optional): Items per page (default: 20)
* `search` (optional): Search term

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "workspace-123",
      "name": "My Workspace",
      "description": "Workspace description",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z",
      "documentCount": 25,
      "userCount": 3
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 1,
    "totalPages": 1
  }
}
```

#### Get Workspace <a href="#get-workspace" id="get-workspace"></a>

```http
GET /workspaces/{workspaceId}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "workspace-123",
    "name": "My Workspace",
    "description": "Workspace description",
    "settings": {
      "aiModel": "gpt-4",
      "temperature": 0.7,
      "maxTokens": 2000
    },
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z",
    "documentCount": 25,
    "userCount": 3
  }
}
```

#### Create Workspace <a href="#create-workspace" id="create-workspace"></a>

```http
POST /workspaces
```

**Request Body:**

```json
{
  "name": "New Workspace",
  "description": "Workspace description",
  "settings": {
    "aiModel": "gpt-4",
    "temperature": 0.7,
    "maxTokens": 2000
  }
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "workspace-456",
    "name": "New Workspace",
    "description": "Workspace description",
    "settings": {
      "aiModel": "gpt-4",
      "temperature": 0.7,
      "maxTokens": 2000
    },
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  }
}
```

#### Update Workspace <a href="#update-workspace" id="update-workspace"></a>

```http
PUT /workspaces/{workspaceId}
```

**Request Body:**

```json
{
  "name": "Updated Workspace",
  "description": "Updated description",
  "settings": {
    "aiModel": "gpt-4",
    "temperature": 0.5,
    "maxTokens": 3000
  }
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "workspace-123",
    "name": "Updated Workspace",
    "description": "Updated description",
    "settings": {
      "aiModel": "gpt-4",
      "temperature": 0.5,
      "maxTokens": 3000
    },
    "updatedAt": "2024-01-15T11:00:00Z"
  }
}
```

#### Delete Workspace <a href="#delete-workspace" id="delete-workspace"></a>

```http
DELETE /workspaces/{workspaceId}
```

**Response:**

```json
{
  "success": true,
  "message": "Workspace deleted successfully"
}
```

### Document Endpoints <a href="#document-endpoints" id="document-endpoints"></a>

#### List Documents <a href="#list-documents" id="list-documents"></a>

```http
GET /workspaces/{workspaceId}/documents
```

**Query Parameters:**

* `page` (optional): Page number
* `limit` (optional): Items per page
* `search` (optional): Search term
* `type` (optional): Document type filter

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "doc-123",
      "name": "document.pdf",
      "type": "pdf",
      "size": 1024000,
      "status": "processed",
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:35:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 1,
    "totalPages": 1
  }
}
```

#### Upload Document <a href="#upload-document" id="upload-document"></a>

```http
POST /workspaces/{workspaceId}/documents
```

**Request Body (multipart/form-data):**

```
file: [binary file data]
name: "document.pdf"
description: "Document description"
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "doc-123",
    "name": "document.pdf",
    "type": "pdf",
    "size": 1024000,
    "status": "processing",
    "createdAt": "2024-01-15T10:30:00Z"
  },
  "message": "Document uploaded successfully"
}
```

#### Get Document <a href="#get-document" id="get-document"></a>

```http
GET /workspaces/{workspaceId}/documents/{documentId}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "doc-123",
    "name": "document.pdf",
    "type": "pdf",
    "size": 1024000,
    "status": "processed",
    "metadata": {
      "pages": 10,
      "language": "en",
      "created": "2024-01-15T10:30:00Z"
    },
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:35:00Z"
  }
}
```

#### Delete Document <a href="#delete-document" id="delete-document"></a>

```http
DELETE /workspaces/{workspaceId}/documents/{documentId}
```

**Response:**

```json
{
  "success": true,
  "message": "Document deleted successfully"
}
```

### Chat Endpoints <a href="#chat-endpoints" id="chat-endpoints"></a>

#### Send Message <a href="#send-message" id="send-message"></a>

```http
POST /workspaces/{workspaceId}/chat
```

**Request Body:**

```json
{
  "message": "What is this document about?",
  "conversationId": "conv-123",
  "options": {
    "temperature": 0.7,
    "maxTokens": 1000
  }
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "msg-456",
    "message": "What is this document about?",
    "response": "This document is about...",
    "conversationId": "conv-123",
    "sources": [
      {
        "documentId": "doc-123",
        "documentName": "document.pdf",
        "page": 1,
        "snippet": "Relevant text snippet..."
      }
    ],
    "createdAt": "2024-01-15T10:30:00Z"
  }
}
```

#### Get Conversation History <a href="#get-conversation-history" id="get-conversation-history"></a>

```http
GET /workspaces/{workspaceId}/chat/{conversationId}
```

**Query Parameters:**

* `page` (optional): Page number
* `limit` (optional): Messages per page

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "conv-123",
    "messages": [
      {
        "id": "msg-456",
        "role": "user",
        "message": "What is this document about?",
        "createdAt": "2024-01-15T10:30:00Z"
      },
      {
        "id": "msg-457",
        "role": "assistant",
        "message": "This document is about...",
        "sources": [
          {
            "documentId": "doc-123",
            "documentName": "document.pdf",
            "page": 1,
            "snippet": "Relevant text snippet..."
          }
        ],
        "createdAt": "2024-01-15T10:30:05Z"
      }
    ],
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:05Z"
  }
}
```

#### List Conversations <a href="#list-conversations" id="list-conversations"></a>

```http
GET /workspaces/{workspaceId}/chat
```

**Query Parameters:**

* `page` (optional): Page number
* `limit` (optional): Conversations per page

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "conv-123",
      "title": "Document Analysis",
      "messageCount": 10,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:35:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 1,
    "totalPages": 1
  }
}
```

### Search Endpoints <a href="#search-endpoints" id="search-endpoints"></a>

#### Search Documents <a href="#search-documents" id="search-documents"></a>

```http
POST /workspaces/{workspaceId}/search
```

**Request Body:**

```json
{
  "query": "search term",
  "type": "semantic",
  "filters": {
    "documentType": "pdf",
    "dateRange": {
      "start": "2024-01-01",
      "end": "2024-12-31"
    }
  },
  "options": {
    "maxResults": 20,
    "includeSnippets": true
  }
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "query": "search term",
    "results": [
      {
        "documentId": "doc-123",
        "documentName": "document.pdf",
        "score": 0.95,
        "snippet": "Relevant text snippet...",
        "page": 1,
        "highlightedTerms": ["search", "term"]
      }
    ],
    "totalResults": 1,
    "searchTime": 0.15
  }
}
```

### User Management Endpoints <a href="#user-management-endpoints" id="user-management-endpoints"></a>

#### List Users <a href="#list-users" id="list-users"></a>

```http
GET /users
```

**Query Parameters:**

* `page` (optional): Page number
* `limit` (optional): Items per page
* `role` (optional): Filter by role
* `status` (optional): Filter by status

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "user-123",
      "email": "user@example.com",
      "name": "John Doe",
      "role": "user",
      "status": "active",
      "createdAt": "2024-01-15T10:30:00Z",
      "lastActive": "2024-01-15T10:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 1,
    "totalPages": 1
  }
}
```

#### Create User <a href="#create-user" id="create-user"></a>

```http
POST /users
```

**Request Body:**

```json
{
  "email": "newuser@example.com",
  "firstName": "Jane",
  "lastName": "Doe",
  "role": "user",
  "workspaces": ["workspace-123"]
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "user-456",
    "email": "newuser@example.com",
    "name": "Jane Doe",
    "role": "user",
    "status": "pending",
    "createdAt": "2024-01-15T10:30:00Z"
  },
  "message": "User created successfully"
}
```

#### Update User <a href="#update-user" id="update-user"></a>

```http
PUT /users/{userId}
```

**Request Body:**

```json
{
  "firstName": "Jane",
  "lastName": "Smith",
  "role": "workspace_admin",
  "workspaces": ["workspace-123", "workspace-456"]
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "id": "user-456",
    "email": "newuser@example.com",
    "name": "Jane Smith",
    "role": "workspace_admin",
    "status": "active",
    "updatedAt": "2024-01-15T11:00:00Z"
  }
}
```

### System Endpoints <a href="#system-endpoints" id="system-endpoints"></a>

#### Health Check <a href="#health-check" id="health-check"></a>

```http
GET /system/health
```

**Response:**

```json
{
  "success": true,
  "data": {
    "status": "healthy",
    "timestamp": "2024-01-15T10:30:00Z",
    "version": "1.8.5",
    "services": {
      "database": "healthy",
      "redis": "healthy",
      "vectorDb": "healthy",
      "aiProvider": "healthy"
    }
  }
}
```

#### System Information <a href="#system-information" id="system-information"></a>

```http
GET /system/info
```

**Response:**

```json
{
  "success": true,
  "data": {
    "version": "1.8.5",
    "buildDate": "2024-01-15T10:00:00Z",
    "environment": "production",
    "features": [
      "multi_user",
      "advanced_analytics",
      "api_access"
    ],
    "limits": {
      "maxWorkspaces": 50,
      "maxDocuments": 1000,
      "maxUsers": 100
    }
  }
}
```

### Error Codes <a href="#error-codes" id="error-codes"></a>

#### Common Error Codes <a href="#common-error-codes" id="common-error-codes"></a>

* `400` - Bad Request
* `401` - Unauthorized
* `403` - Forbidden
* `404` - Not Found
* `409` - Conflict
* `422` - Validation Error
* `429` - Rate Limit Exceeded
* `500` - Internal Server Error
* `503` - Service Unavailable

#### Error Response Format <a href="#error-response-format" id="error-response-format"></a>

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input parameters",
    "details": {
      "field": "email",
      "reason": "Invalid email format"
    },
    "timestamp": "2024-01-15T10:30:00Z",
    "requestId": "req-123"
  }
}
```

### Rate Limiting <a href="#rate-limiting" id="rate-limiting"></a>

#### Rate Limits <a href="#rate-limits" id="rate-limits"></a>

* **Authentication**: 5 requests per minute
* **General API**: 100 requests per minute
* **Document Upload**: 10 requests per minute
* **Chat**: 50 requests per minute

#### Rate Limit Headers <a href="#rate-limit-headers" id="rate-limit-headers"></a>

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642248600
```

### SDKs and Libraries <a href="#sdks-and-libraries" id="sdks-and-libraries"></a>

#### JavaScript/Node.js <a href="#javascriptnodejs" id="javascriptnodejs"></a>

```bash
npm install ainexlayer-sdk
```

```javascript
const AINexLayer = require('ainexlayer-sdk');

const client = new AINexLayer({
  apiKey: 'your-api-key',
  baseUrl: 'https://api.ainexlayer.com'
});

// Create workspace
const workspace = await client.workspaces.create({
  name: 'My Workspace',
  description: 'Workspace description'
});

// Upload document
const document = await client.documents.upload(workspace.id, {
  file: fileBuffer,
  name: 'document.pdf'
});

// Send chat message
const response = await client.chat.send(workspace.id, {
  message: 'What is this document about?'
});
```

#### Python <a href="#python" id="python"></a>

```bash
pip install ainexlayer-sdk
```

```python
from ainexlayer import AINexLayer

client = AINexLayer(
    api_key='your-api-key',
    base_url='https://api.ainexlayer.com'
)

# Create workspace
workspace = client.workspaces.create(
    name='My Workspace',
    description='Workspace description'
)

# Upload document
with open('document.pdf', 'rb') as f:
    document = client.documents.upload(
        workspace_id=workspace.id,
        file=f,
        name='document.pdf'
    )

# Send chat message
response = client.chat.send(
    workspace_id=workspace.id,
    message='What is this document about?'
)
```

### Webhooks <a href="#webhooks" id="webhooks"></a>

#### Webhook Configuration <a href="#webhook-configuration" id="webhook-configuration"></a>

```http
POST /webhooks
```

**Request Body:**

```json
{
  "url": "https://your-app.com/webhook",
  "events": [
    "document.uploaded",
    "document.processed",
    "chat.message",
    "workspace.created"
  ],
  "secret": "webhook-secret"
}
```

#### Webhook Payload <a href="#webhook-payload" id="webhook-payload"></a>

```json
{
  "event": "document.processed",
  "timestamp": "2024-01-15T10:30:00Z",
  "data": {
    "workspaceId": "workspace-123",
    "documentId": "doc-123",
    "status": "processed",
    "metadata": {
      "pages": 10,
      "language": "en"
    }
  }
}
```

***

**🔌 The AINexLayer API provides comprehensive programmatic access to all platform features. Use this reference to integrate AINexLayer into your applications.**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.ainexlayer.com/documentation/integration-guides/api-documentation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
