# Overview

BroxiAI provides a comprehensive REST API for integrating your workflows into external applications, automating processes, and building custom solutions.

## API Architecture

<figure><img src="https://2739525811-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FGUcjvdv7MzVy7GYqImRT%2Fuploads%2FNx98hpUOwuOuFv4EExRf%2FUntitled%20diagram%20_%20Mermaid%20Chart-2025-09-07-155002.png?alt=media&#x26;token=bfb7ae52-939a-4a3c-9b7c-ec87843b8ce1" alt=""><figcaption></figcaption></figure>

## Base URL

All API requests should be made to:

```
https://api.broxi.ai/v1
```

## Authentication

BroxiAI uses API tokens for authentication. Include your token in the Authorization header:

```bash
Authorization: Bearer YOUR_API_TOKEN
```

### Getting Your API Token

1. Log into your BroxiAI dashboard
2. Navigate to Settings → API Keys
3. Generate a new API token
4. Copy and securely store your token

{% hint style="warning" %}
Keep your API tokens secure and never expose them in client-side code. Tokens have the same permissions as your user account.
{% endhint %}

## Core Endpoints

### Workflows

#### Run a Workflow

Execute a published workflow with input data.

```http
POST /v1/flows/{flow_id}/run
```

**Parameters**

* `flow_id` (string, required): The unique identifier of your workflow

**Request Body**

```json
{
  "input": "Your input message or data",
  "session_id": "optional-session-id",
  "stream": false,
  "variables": {
    "custom_variable": "value"
  }
}
```

**Response**

```json
{
  "id": "run_12345",
  "flow_id": "flow_abc123",
  "status": "completed",
  "output": "Generated response from workflow",
  "created_at": "2024-01-15T10:30:00Z",
  "completed_at": "2024-01-15T10:30:05Z",
  "usage": {
    "total_tokens": 150,
    "prompt_tokens": 100,
    "completion_tokens": 50
  }
}
```

#### Stream Workflow Execution

Execute a workflow with real-time streaming response.

```http
POST /v1/flows/{flow_id}/stream
```

**Request Body**

```json
{
  "input": "Your input message",
  "session_id": "session_abc123"
}
```

**Response** (Server-Sent Events)

```
data: {"type": "start", "run_id": "run_12345"}

data: {"type": "token", "content": "Hello"}

data: {"type": "token", "content": " world"}

data: {"type": "end", "run_id": "run_12345", "usage": {...}}
```

#### Get Workflow Status

Check the status of a running workflow.

```http
GET /v1/runs/{run_id}
```

**Response**

```json
{
  "id": "run_12345",
  "flow_id": "flow_abc123",
  "status": "running|completed|failed",
  "progress": 75,
  "output": "Partial or complete output",
  "error": null,
  "created_at": "2024-01-15T10:30:00Z"
}
```

### Flow Management

#### List Workflows

Get all your published workflows.

```http
GET /v1/flows
```

**Query Parameters**

* `limit` (integer): Number of flows to return (default: 20, max: 100)
* `offset` (integer): Number of flows to skip (default: 0)
* `status` (string): Filter by status (`published`, `draft`)

**Response**

```json
{
  "flows": [
    {
      "id": "flow_abc123",
      "name": "Customer Support Bot",
      "description": "AI assistant for customer inquiries",
      "status": "published",
      "created_at": "2024-01-10T09:00:00Z",
      "updated_at": "2024-01-15T14:30:00Z",
      "endpoint": "https://api.broxi.ai/v1/flows/flow_abc123/run"
    }
  ],
  "total": 5,
  "limit": 20,
  "offset": 0
}
```

#### Get Workflow Details

Retrieve detailed information about a specific workflow.

```http
GET /v1/flows/{flow_id}
```

**Response**

```json
{
  "id": "flow_abc123",
  "name": "Customer Support Bot",
  "description": "AI assistant for customer inquiries",
  "status": "published",
  "config": {
    "input_schema": {
      "type": "object",
      "properties": {
        "message": {"type": "string"},
        "user_id": {"type": "string"}
      }
    },
    "output_schema": {
      "type": "object",
      "properties": {
        "response": {"type": "string"},
        "confidence": {"type": "number"}
      }
    }
  },
  "created_at": "2024-01-10T09:00:00Z",
  "updated_at": "2024-01-15T14:30:00Z"
}
```

### Session Management

#### Create Session

Create a new conversation session for stateful interactions.

```http
POST /v1/sessions
```

**Request Body**

```json
{
  "flow_id": "flow_abc123",
  "user_id": "user_xyz789",
  "metadata": {
    "source": "web_app",
    "version": "1.0"
  }
}
```

**Response**

```json
{
  "id": "session_def456",
  "flow_id": "flow_abc123",
  "user_id": "user_xyz789",
  "status": "active",
  "created_at": "2024-01-15T10:00:00Z",
  "metadata": {
    "source": "web_app",
    "version": "1.0"
  }
}
```

#### Get Session History

Retrieve conversation history for a session.

```http
GET /v1/sessions/{session_id}/history
```

**Response**

```json
{
  "session_id": "session_def456",
  "messages": [
    {
      "id": "msg_001",
      "role": "user",
      "content": "Hello, I need help",
      "timestamp": "2024-01-15T10:00:00Z"
    },
    {
      "id": "msg_002", 
      "role": "assistant",
      "content": "How can I assist you today?",
      "timestamp": "2024-01-15T10:00:05Z"
    }
  ],
  "total": 2
}
```

### Analytics

#### Get Usage Statistics

Retrieve usage metrics for your workflows.

```http
GET /v1/analytics/usage
```

**Query Parameters**

* `start_date` (string): Start date (ISO 8601 format)
* `end_date` (string): End date (ISO 8601 format)
* `flow_id` (string): Filter by specific workflow
* `granularity` (string): Data granularity (`hour`, `day`, `week`, `month`)

**Response**

```json
{
  "period": {
    "start": "2024-01-01T00:00:00Z",
    "end": "2024-01-31T23:59:59Z"
  },
  "metrics": {
    "total_runs": 1250,
    "successful_runs": 1180,
    "failed_runs": 70,
    "total_tokens": 125000,
    "avg_response_time": 2.3,
    "cost": 15.75
  },
  "daily_breakdown": [
    {
      "date": "2024-01-01",
      "runs": 45,
      "tokens": 4500,
      "cost": 0.68
    }
  ]
}
```

## Error Handling

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

### Error Response Format

```json
{
  "error": {
    "code": "INVALID_REQUEST",
    "message": "The request body is invalid",
    "details": {
      "field": "input",
      "reason": "Required field is missing"
    }
  },
  "request_id": "req_abc123"
}
```

### Common Error Codes

| Code                  | Status | Description                          |
| --------------------- | ------ | ------------------------------------ |
| `INVALID_REQUEST`     | 400    | Invalid request format or parameters |
| `UNAUTHORIZED`        | 401    | Invalid or missing API token         |
| `FORBIDDEN`           | 403    | Insufficient permissions             |
| `NOT_FOUND`           | 404    | Resource not found                   |
| `RATE_LIMITED`        | 429    | Too many requests                    |
| `INTERNAL_ERROR`      | 500    | Server error                         |
| `SERVICE_UNAVAILABLE` | 503    | Service temporarily unavailable      |

## Rate Limits

API requests are rate limited to ensure fair usage:

* **Free Tier**: 100 requests per minute
* **Pro Tier**: 1,000 requests per minute
* **Enterprise**: Custom limits

Rate limit headers are included in responses:

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642694400
```

## Webhooks

Configure webhooks to receive real-time notifications about workflow events.

### Webhook Events

* `flow.run.started`: Workflow execution began
* `flow.run.completed`: Workflow execution finished successfully
* `flow.run.failed`: Workflow execution failed
* `session.created`: New session created
* `session.ended`: Session ended

### Webhook Payload

```json
{
  "event": "flow.run.completed",
  "data": {
    "run_id": "run_12345",
    "flow_id": "flow_abc123",
    "status": "completed",
    "output": "Generated response",
    "usage": {
      "total_tokens": 150
    }
  },
  "timestamp": "2024-01-15T10:30:05Z"
}
```

For webhook setup, see [Webhook Configuration](https://guidenai.gitbook.io/broxi/workflows/webhook).

## SDKs and Libraries

Official SDKs are available for popular programming languages:

### Python SDK

```python
from broxi import BroxiClient

client = BroxiClient(api_token="your_token")

# Run a workflow
result = client.flows.run(
    flow_id="flow_abc123",
    input="Hello, world!"
)
print(result.output)
```

### JavaScript SDK

```javascript
import { BroxiClient } from '@broxi/sdk';

const client = new BroxiClient({
  apiToken: 'your_token'
});

// Run a workflow
const result = await client.flows.run({
  flowId: 'flow_abc123',
  input: 'Hello, world!'
});
console.log(result.output);
```

### cURL Examples

#### Basic Workflow Execution

```bash
curl -X POST "https://api.broxi.ai/v1/flows/flow_abc123/run" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "What is the weather like today?",
    "variables": {
      "location": "San Francisco"
    }
  }'
```

#### Streaming Response

```bash
curl -X POST "https://api.broxi.ai/v1/flows/flow_abc123/stream" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "input": "Tell me a story",
    "session_id": "session_123"
  }'
```

## Best Practices

### Performance Optimization

1. **Use Sessions**: For conversational flows, use sessions to maintain context
2. **Batch Requests**: Group multiple operations when possible
3. **Caching**: Cache responses for repeated queries
4. **Streaming**: Use streaming for long-running operations

### Security

1. **Secure Storage**: Store API tokens securely
2. **Token Rotation**: Rotate tokens regularly
3. **Network Security**: Use HTTPS for all requests
4. **Input Validation**: Validate all user inputs

### Error Handling

1. **Retry Logic**: Implement exponential backoff for retries
2. **Circuit Breakers**: Prevent cascading failures
3. **Logging**: Log API interactions for debugging
4. **Monitoring**: Monitor API usage and errors

## Support

For API support:

* Check our [troubleshooting guide](https://guidenai.gitbook.io/broxi/help-and-support/troubleshooting)
* Review [code examples](https://github.com/GuidenAI/broxi_document/blob/main/examples/api-integration.md)
* Contact technical support
* Join our developer community
