> For the complete documentation index, see [llms.txt](https://docs.meganova.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.meganova.ai/character-studio/advanced/api-integration.md).

# API Integration

> **Note:** Character Studio provides API access for programmatic character management and chat interactions. Use the API to integrate characters into your applications.

## Overview

The Character Studio API allows:

* **Character management** — CRUD operations
* **Chat integration** — Message streaming
* **Asset management** — Images and files
* **Analytics access** — Usage data

## Authentication

### API Keys

1. Go to **Settings** → **API Keys**
2. Click **Create API Key**
3. Copy and store securely

### Using API Keys

Include in headers:

```
Authorization: Bearer YOUR_API_KEY
```

## Base URLs

| Environment   | URL                              |
| ------------- | -------------------------------- |
| Production    | `https://studio-api.meganova.ai` |
| API Reference | `https://api.meganova.ai`        |

## Character Endpoints

### List Characters

```http
GET /api/characters
```

**Response:**

```json
{
  "characters": [
    {
      "id": "uuid",
      "name": "Elena",
      "description": "...",
      "created_at": "2024-01-15T..."
    }
  ],
  "total": 10,
  "page": 1
}
```

### Get Character

```http
GET /api/characters/{id}
```

**Response:**

```json
{
  "id": "uuid",
  "name": "Elena",
  "description": "...",
  "personality": "...",
  "scenario": "...",
  "first_message": "...",
  "example_dialogues": "...",
  ...
}
```

### Create Character

```http
POST /api/characters
Content-Type: application/json

{
  "name": "New Character",
  "description": "...",
  "first_message": "Hello!"
}
```

### Update Character

```http
PUT /api/characters/{id}
Content-Type: application/json

{
  "name": "Updated Name",
  "description": "Updated description"
}
```

### Delete Character

```http
DELETE /api/characters/{id}
```

## Chat Endpoints

### Send Message

```http
POST /api/chat/{character_id}/messages
Content-Type: application/json

{
  "content": "Hello!",
  "session_id": "optional-session-id"
}
```

### Stream Response

```http
POST /api/chat/{character_id}/stream
Content-Type: application/json
Accept: text/event-stream

{
  "content": "Hello!",
  "session_id": "session-id"
}
```

**Response (SSE):**

```
data: {"token": "Hello"}
data: {"token": " there"}
data: {"token": "!"}
data: [DONE]
```

### Get Chat History

```http
GET /api/chat/sessions/{session_id}/messages
```

## Code Examples

### Python

```python
import requests

API_KEY = "your_api_key"
BASE_URL = "https://studio-api.meganova.ai"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# List characters
response = requests.get(
    f"{BASE_URL}/api/characters",
    headers=headers
)
characters = response.json()

# Send chat message
response = requests.post(
    f"{BASE_URL}/api/chat/{character_id}/messages",
    headers=headers,
    json={"content": "Hello!"}
)
reply = response.json()
```

### JavaScript

```javascript
const API_KEY = 'your_api_key';
const BASE_URL = 'https://studio-api.meganova.ai';

const headers = {
  'Authorization': `Bearer ${API_KEY}`,
  'Content-Type': 'application/json'
};

// List characters
const response = await fetch(`${BASE_URL}/api/characters`, {
  headers
});
const { characters } = await response.json();

// Send chat message
const chatResponse = await fetch(
  `${BASE_URL}/api/chat/${characterId}/messages`,
  {
    method: 'POST',
    headers,
    body: JSON.stringify({ content: 'Hello!' })
  }
);
const reply = await chatResponse.json();
```

### Streaming Example

```javascript
const response = await fetch(
  `${BASE_URL}/api/chat/${characterId}/stream`,
  {
    method: 'POST',
    headers: {
      ...headers,
      'Accept': 'text/event-stream'
    },
    body: JSON.stringify({ content: 'Hello!' })
  }
);

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { value, done } = await reader.read();
  if (done) break;

  const chunk = decoder.decode(value);
  // Parse SSE events
  console.log(chunk);
}
```

## Rate Limits

| Tier       | Requests/min | Chat/min |
| ---------- | ------------ | -------- |
| Free       | 60           | 30       |
| Pro        | 300          | 120      |
| Enterprise | 1000         | 500      |

## Error Handling

### Error Response Format

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human readable message",
    "details": {}
  }
}
```

### Common Errors

| Code             | Status | Meaning            |
| ---------------- | ------ | ------------------ |
| `UNAUTHORIZED`   | 401    | Invalid API key    |
| `FORBIDDEN`      | 403    | Access denied      |
| `NOT_FOUND`      | 404    | Resource not found |
| `RATE_LIMITED`   | 429    | Too many requests  |
| `INTERNAL_ERROR` | 500    | Server error       |

## Webhooks (Coming)

Register webhooks for events:

```http
POST /api/webhooks
Content-Type: application/json

{
  "url": "https://yoursite.com/webhook",
  "events": ["chat.message", "character.updated"]
}
```

## See Also

* [API Reference](https://docs.meganova.ai/api-reference.md) — Full API documentation
* [Character Specs](https://docs.meganova.ai/character-studio/advanced/character-specs.md) — Data formats
* [Embed Widgets](https://docs.meganova.ai/character-studio/embed-widgets.md) — Widget integration
