# Yemaya API Reference

Complete reference documentation for the Yemaya REST API.

## Overview

The Yemaya API provides programmatic access to the creative production platform,
enabling management of projects, assets, teams, and workflows.

**Base URLs:**

- Production: `https://api.yemaya.io/v1`
- Staging: `https://api.staging.yemaya.io/v1`
- Local Development: `http://localhost:3000/v1`

**OpenAPI Specification:** Available at `/openapi.json`

**Interactive Documentation:**

- Swagger UI: `/docs`
- Scalar Reference: `/reference`

## Authentication

### Bearer Token (JWT)

Most API endpoints require authentication via JWT bearer tokens. Include the
token in the `Authorization` header:

```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**Token Lifecycle:**

- Access tokens expire after 15 minutes
- Refresh tokens are valid for 7 days
- Use `POST /auth/refresh` to obtain new access tokens

### API Keys

For server-to-server communication, use API keys:

```http
X-API-Key: yek_live_abc123def456...
```

API keys can be created with specific scopes to limit permissions.

## Rate Limiting

| Authentication  | Limit                |
| --------------- | -------------------- |
| Authenticated   | 1000 requests/minute |
| Unauthenticated | 60 requests/minute   |

Rate limit headers are included in all responses:

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1702345678
```

## Response Format

### Success Response

```json
{
  "success": true,
  "data": { ... }
}
```

### Paginated Response

```json
{
  "data": [ ... ],
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "totalPages": 8,
    "hasMore": true
  }
}
```

### Error Response

```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request data",
    "details": {
      "email": ["Invalid email format"]
    }
  }
}
```

## HTTP Status Codes

| Code  | Description                             |
| ----- | --------------------------------------- |
| `200` | Success                                 |
| `201` | Created                                 |
| `400` | Bad Request - Invalid input             |
| `401` | Unauthorized - Missing or invalid token |
| `403` | Forbidden - Insufficient permissions    |
| `404` | Not Found                               |
| `409` | Conflict - Resource already exists      |
| `429` | Too Many Requests - Rate limited        |
| `500` | Internal Server Error                   |

---

## Authentication Endpoints

### Register User

Create a new user account.

```http
POST /auth/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "securePassword123!",
  "name": "John Doe",
  "acceptedTerms": true
}
```

**Response (201 Created):**

```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "user@example.com",
      "name": "John Doe",
      "emailVerified": false,
      "createdAt": "2024-01-15T10:30:00Z"
    },
    "tokens": {
      "accessToken": "eyJhbG...",
      "refreshToken": "ref_abc123...",
      "expiresIn": 900
    }
  }
}
```

### Login

Authenticate with email and password.

```http
POST /auth/login
Content-Type: application/json

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

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "user": {
      "id": "usr_abc123",
      "email": "user@example.com",
      "name": "John Doe"
    },
    "tokens": {
      "accessToken": "eyJhbG...",
      "refreshToken": "ref_abc123...",
      "expiresIn": 900
    }
  }
}
```

### Refresh Token

Get a new access token using a refresh token.

```http
POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "ref_abc123..."
}
```

### Logout

Invalidate current session.

```http
POST /auth/logout
Authorization: Bearer <token>
```

### OAuth Login

Initiate OAuth flow with a provider.

```http
GET /auth/oauth/{provider}?redirect=https://app.yemaya.io/callback
```

**Supported Providers:** `google`, `github`, `discord`, `apple`

OAuth callbacks are handled at:

```http
GET /auth/oauth/{provider}/callback
```

On success, the API redirects to the `redirect` URL with tokens encoded in the
URL fragment.

### Password Reset

Request a password reset email.

```http
POST /auth/password/reset
Content-Type: application/json

{
  "email": "user@example.com"
}
```

### Confirm Password Reset

Set a new password using reset token.

```http
POST /auth/password/reset/confirm
Content-Type: application/json

{
  "token": "rst_abc123...",
  "password": "newSecurePassword123!"
}
```

### Verify Email

Verify email address with token.

```http
POST /auth/email/verify
Content-Type: application/json

{
  "token": "ver_abc123..."
}
```

---

## Session Management

### List Sessions

Get all active sessions for the current user.

```http
GET /auth/sessions
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "sess_abc123",
      "device": "Chrome on macOS",
      "ip": "192.168.1.1",
      "location": "San Francisco, CA",
      "lastActive": "2024-01-15T10:30:00Z",
      "current": true
    }
  ]
}
```

### Revoke Session

Revoke a specific session (logout from device).

```http
DELETE /auth/sessions/{sessionId}
Authorization: Bearer <token>
```

### Revoke All Sessions

Logout from all devices except current.

```http
DELETE /auth/sessions
Authorization: Bearer <token>
```

---

## API Key Management

### List API Keys

Get all API keys for the current user.

```http
GET /auth/api-keys
Authorization: Bearer <token>
```

### Create API Key

Create a new API key with specific scopes.

```http
POST /auth/api-keys
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "CI/CD Pipeline",
  "scopes": ["projects:read", "assets:read", "assets:write"],
  "expiresAt": "2025-01-15T00:00:00Z"
}
```

**Response (201 Created):**

```json
{
  "success": true,
  "data": {
    "id": "key_abc123",
    "name": "CI/CD Pipeline",
    "key": "yek_live_abc123def456...",
    "scopes": ["projects:read", "assets:read", "assets:write"],
    "expiresAt": "2025-01-15T00:00:00Z"
  },
  "message": "Store this key securely - it won't be shown again"
}
```

**Available Scopes:**

| Scope                 | Description            |
| --------------------- | ---------------------- |
| `projects:read`       | Read project data      |
| `projects:write`      | Create/update projects |
| `projects:delete`     | Delete projects        |
| `assets:read`         | Read asset data        |
| `assets:write`        | Upload/update assets   |
| `assets:delete`       | Delete assets          |
| `users:read`          | Read user profiles     |
| `organizations:read`  | Read organization data |
| `organizations:write` | Manage organizations   |

### Delete API Key

Revoke and delete an API key.

```http
DELETE /auth/api-keys/{keyId}
Authorization: Bearer <token>
```

---

## Projects

### List Projects

Get paginated list of projects accessible to the current user.

```http
GET /projects?page=1&limit=20&status=active&type=game
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter        | Type    | Description                                                  |
| ---------------- | ------- | ------------------------------------------------------------ |
| `page`           | number  | Page number (default: 1)                                     |
| `limit`          | number  | Items per page (default: 20, max: 100)                       |
| `status`         | string  | Filter by status: `draft`, `active`, `archived`, `completed` |
| `type`           | string  | Filter by type: `film`, `game`, `animation`, `mixed`         |
| `visibility`     | string  | Filter by visibility: `private`, `team`, `public`            |
| `organizationId` | uuid    | Filter by organization                                       |
| `search`         | string  | Search in name and description                               |
| `owned`          | boolean | Filter to owned projects only                                |

**Response:**

```json
{
  "data": [
    {
      "id": "proj_abc123",
      "name": "Space Adventure",
      "description": "A sci-fi game project",
      "type": "game",
      "status": "active",
      "visibility": "team",
      "thumbnailUrl": "https://cdn.yemaya.io/...",
      "owner": {
        "id": "usr_abc123",
        "name": "John Doe"
      },
      "organization": {
        "id": "org_abc123",
        "name": "Game Studio Inc"
      },
      "memberCount": 5,
      "assetCount": 150,
      "createdAt": "2024-01-10T08:00:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 45,
    "totalPages": 3,
    "hasMore": true
  }
}
```

### Create Project

Create a new project.

```http
POST /projects
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "My New Project",
  "description": "An exciting new game",
  "type": "game",
  "visibility": "team",
  "organizationId": "org_abc123",
  "settings": {
    "targetPlatforms": ["pc", "console"],
    "gameEngine": "godot"
  },
  "tags": ["rpg", "indie"]
}
```

**Project Types:**

| Type        | Description         |
| ----------- | ------------------- |
| `film`      | Film/movie project  |
| `game`      | Video game project  |
| `animation` | Animation project   |
| `mixed`     | Mixed media project |

### Get Project

Get project details by ID.

```http
GET /projects/{projectId}
Authorization: Bearer <token>
```

### Update Project

Update project details.

```http
PATCH /projects/{projectId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Updated Project Name",
  "description": "Updated description",
  "status": "completed"
}
```

### Delete Project

Permanently delete a project and all its contents.

```http
DELETE /projects/{projectId}
Authorization: Bearer <token>
```

### Archive Project

Archive a project (can be restored later).

```http
POST /projects/{projectId}/archive
Authorization: Bearer <token>
```

### Restore Project

Restore an archived project.

```http
POST /projects/{projectId}/restore
Authorization: Bearer <token>
```

### Duplicate Project

Create a copy of a project.

```http
POST /projects/{projectId}/duplicate
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "My Project (Copy)",
  "includeAssets": true
}
```

### Upload Thumbnail

Upload a thumbnail image for the project.

```http
POST /projects/{projectId}/thumbnail
Authorization: Bearer <token>
Content-Type: multipart/form-data

file: <binary>
```

---

## Project Members

### List Members

Get all members of a project.

```http
GET /projects/{projectId}/members
Authorization: Bearer <token>
```

**Response:**

```json
{
  "data": [
    {
      "userId": "usr_abc123",
      "user": {
        "id": "usr_abc123",
        "name": "John Doe",
        "email": "john@example.com",
        "avatarUrl": "https://..."
      },
      "role": "owner",
      "joinedAt": "2024-01-10T08:00:00Z"
    }
  ],
  "meta": { ... }
}
```

**Roles:**

| Role     | Permissions                     |
| -------- | ------------------------------- |
| `owner`  | Full access, can delete project |
| `admin`  | Manage members, edit settings   |
| `editor` | Create/edit content             |
| `viewer` | Read-only access                |

### Add Member

Invite a user to the project.

```http
POST /projects/{projectId}/members
Authorization: Bearer <token>
Content-Type: application/json

{
  "userId": "usr_def456",
  "role": "editor"
}
```

Or invite by email:

```json
{
  "email": "newuser@example.com",
  "role": "editor"
}
```

### Update Member Role

Update a member's role in the project.

```http
PATCH /projects/{projectId}/members/{userId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "role": "admin"
}
```

### Remove Member

Remove a member from the project.

```http
DELETE /projects/{projectId}/members/{userId}
Authorization: Bearer <token>
```

### Leave Project

Leave a project (cannot leave if you are the only owner).

```http
POST /projects/{projectId}/leave
Authorization: Bearer <token>
```

---

## Project Comments

### List Comments

Get comments for a project.

```http
GET /projects/{projectId}/comments?resourceType=asset&resourceId=ast_123
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter      | Type    | Description                                      |
| -------------- | ------- | ------------------------------------------------ |
| `resourceType` | string  | Filter by resource type (e.g., `asset`, `scene`) |
| `resourceId`   | uuid    | Filter by resource ID                            |
| `resolved`     | boolean | Filter by resolved status                        |

### Create Comment

Add a comment to the project.

```http
POST /projects/{projectId}/comments
Authorization: Bearer <token>
Content-Type: application/json

{
  "content": "This looks great! Can we adjust the lighting?",
  "resourceType": "asset",
  "resourceId": "ast_abc123",
  "position": {
    "x": 150,
    "y": 200
  },
  "parentId": null
}
```

### Update Comment

Update a comment.

```http
PATCH /projects/{projectId}/comments/{commentId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "content": "Updated comment text"
}
```

### Delete Comment

Delete a comment.

```http
DELETE /projects/{projectId}/comments/{commentId}
Authorization: Bearer <token>
```

### Resolve Comment

Mark a comment as resolved.

```http
POST /projects/{projectId}/comments/{commentId}/resolve
Authorization: Bearer <token>
```

---

## Project Activity

### Get Activity

Get activity log for a project.

```http
GET /projects/{projectId}/activity?page=1&limit=50
Authorization: Bearer <token>
```

**Response:**

```json
{
  "data": [
    {
      "id": "act_abc123",
      "type": "asset.uploaded",
      "actor": {
        "id": "usr_abc123",
        "name": "John Doe"
      },
      "target": {
        "type": "asset",
        "id": "ast_abc123",
        "name": "hero_model.fbx"
      },
      "metadata": {
        "fileSize": 15000000,
        "format": "fbx"
      },
      "timestamp": "2024-01-15T10:30:00Z"
    }
  ],
  "meta": { ... }
}
```

---

## Assets

Assets are managed within the context of a project.

### List Assets

Get assets in a project.

```http
GET /projects/{projectId}/assets?type=model&folder=characters
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter | Type     | Description                                                                |
| --------- | -------- | -------------------------------------------------------------------------- |
| `type`    | string   | Filter by type: `model`, `texture`, `audio`, `video`, `script`, `document` |
| `folder`  | string   | Filter by folder path                                                      |
| `search`  | string   | Search in name and tags                                                    |
| `tags`    | string[] | Filter by tags                                                             |

### Upload Asset

Request a presigned URL for direct upload.

```http
POST /projects/{projectId}/assets/upload
Authorization: Bearer <token>
Content-Type: application/json

{
  "filename": "hero_model.fbx",
  "contentType": "application/octet-stream",
  "size": 15000000,
  "folder": "characters"
}
```

**Response:**

```json
{
  "success": true,
  "data": {
    "uploadId": "upl_abc123",
    "uploadUrl": "https://storage.yemaya.io/...",
    "fields": { ... },
    "expiresAt": "2024-01-15T11:00:00Z"
  }
}
```

Then upload directly to the presigned URL:

```http
PUT {uploadUrl}
Content-Type: application/octet-stream

<binary file data>
```

### Confirm Upload

Confirm that upload is complete.

```http
POST /projects/{projectId}/assets/{uploadId}/confirm
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Hero Character Model",
  "description": "Main character 3D model",
  "tags": ["character", "hero", "3d"]
}
```

### Get Asset

Get asset details.

```http
GET /projects/{projectId}/assets/{assetId}
Authorization: Bearer <token>
```

### Update Asset

Update asset metadata.

```http
PATCH /projects/{projectId}/assets/{assetId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Updated Name",
  "description": "Updated description",
  "tags": ["updated", "tags"]
}
```

### Delete Asset

Delete an asset.

```http
DELETE /projects/{projectId}/assets/{assetId}
Authorization: Bearer <token>
```

### Move Asset

Move asset to a different folder.

```http
POST /projects/{projectId}/assets/{assetId}/move
Authorization: Bearer <token>
Content-Type: application/json

{
  "folder": "characters/npcs"
}
```

### Get Download URL

Get a signed download URL.

```http
GET /projects/{projectId}/assets/{assetId}/download
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "url": "https://cdn.yemaya.io/...",
    "expiresAt": "2024-01-15T11:00:00Z"
  }
}
```

---

## Asset Versions

### List Versions

Get version history for an asset.

```http
GET /projects/{projectId}/assets/{assetId}/versions
Authorization: Bearer <token>
```

### Create Version

Upload a new version of an asset.

```http
POST /projects/{projectId}/assets/{assetId}/versions
Authorization: Bearer <token>
Content-Type: application/json

{
  "filename": "hero_model_v2.fbx",
  "contentType": "application/octet-stream",
  "size": 16000000,
  "changelog": "Added facial animations"
}
```

### Restore Version

Restore a previous version as the current version.

```http
POST /projects/{projectId}/assets/{assetId}/versions/{versionId}/restore
Authorization: Bearer <token>
```

---

## Asset Folders

### List Folders

Get folder structure for a project.

```http
GET /projects/{projectId}/folders
Authorization: Bearer <token>
```

### Create Folder

Create a new folder.

```http
POST /projects/{projectId}/folders
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "characters",
  "parent": null
}
```

### Rename Folder

Rename a folder.

```http
PATCH /projects/{projectId}/folders/{folderId}
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "new_name"
}
```

### Delete Folder

Delete a folder and optionally its contents.

```http
DELETE /projects/{projectId}/folders/{folderId}?deleteContents=false
Authorization: Bearer <token>
```

---

## Organizations

### List Organizations

Get organizations the current user is a member of.

```http
GET /organizations
Authorization: Bearer <token>
```

### Create Organization

Create a new organization.

```http
POST /organizations
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Game Studio Inc",
  "slug": "game-studio",
  "description": "Indie game development studio",
  "website": "https://gamestudio.com"
}
```

### Get Organization

Get organization details.

```http
GET /organizations/{organizationId}
Authorization: Bearer <token>
```

### Update Organization

Update organization details.

```http
PATCH /organizations/{organizationId}
Authorization: Bearer <token>
Content-Type: application/json

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

### Delete Organization

Delete an organization (requires owner role).

```http
DELETE /organizations/{organizationId}
Authorization: Bearer <token>
```

---

## Health Checks

### Basic Health

```http
GET /health
```

**Response:**

```json
{
  "status": "healthy",
  "timestamp": "2024-01-15T10:30:00Z",
  "version": "1.0.0"
}
```

### Readiness

```http
GET /health/ready
```

**Response:**

```json
{
  "status": "ready",
  "checks": {
    "database": "healthy",
    "cache": "healthy",
    "storage": "healthy"
  }
}
```

### Liveness

```http
GET /health/live
```

**Response:**

```json
{
  "status": "alive"
}
```

---

## Webhooks

Configure webhooks to receive real-time notifications about events in your
projects.

### Event Types

| Event              | Description                 |
| ------------------ | --------------------------- |
| `project.created`  | Project was created         |
| `project.updated`  | Project was updated         |
| `project.deleted`  | Project was deleted         |
| `asset.uploaded`   | Asset was uploaded          |
| `asset.updated`    | Asset was updated           |
| `asset.deleted`    | Asset was deleted           |
| `member.added`     | Member was added to project |
| `member.removed`   | Member was removed          |
| `comment.created`  | Comment was created         |
| `comment.resolved` | Comment was resolved        |

### Webhook Payload

```json
{
  "id": "evt_abc123",
  "type": "asset.uploaded",
  "timestamp": "2024-01-15T10:30:00Z",
  "data": {
    "projectId": "proj_abc123",
    "assetId": "ast_abc123",
    "name": "hero_model.fbx",
    "uploadedBy": {
      "id": "usr_abc123",
      "name": "John Doe"
    }
  }
}
```

### Webhook Signature

Verify webhook authenticity using the `X-Webhook-Signature` header:

```typescript
import crypto from 'crypto';

function verifyWebhook(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expected}`)
  );
}
```

---

## SDK Examples

### TypeScript/JavaScript

```typescript
import { YemayaClient } from '@yemaya/sdk';

const client = new YemayaClient({
  apiKey: 'yek_live_abc123...',
  // or
  accessToken: 'eyJhbG...',
});

// List projects
const projects = await client.projects.list({
  status: 'active',
  limit: 10,
});

// Create project
const project = await client.projects.create({
  name: 'My Game',
  type: 'game',
});

// Upload asset
const asset = await client.assets.upload(project.id, {
  file: fs.readFileSync('model.fbx'),
  name: 'Character Model',
  folder: 'characters',
});
```

### Python

```python
from yemaya import YemayaClient

client = YemayaClient(api_key="yek_live_abc123...")

# List projects
projects = client.projects.list(status="active", limit=10)

# Create project
project = client.projects.create(
    name="My Game",
    type="game"
)

# Upload asset
with open("model.fbx", "rb") as f:
    asset = client.assets.upload(
        project_id=project.id,
        file=f,
        name="Character Model",
        folder="characters"
    )
```

### cURL

```bash
# Authenticate
TOKEN=$(curl -s -X POST https://api.yemaya.io/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password"}' \
  | jq -r '.data.tokens.accessToken')

# List projects
curl -s https://api.yemaya.io/v1/projects \
  -H "Authorization: Bearer $TOKEN" \
  | jq

# Create project
curl -s -X POST https://api.yemaya.io/v1/projects \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"My Project","type":"game"}'
```

---

## Error Codes

| Code                       | Description                     | Resolution                              |
| -------------------------- | ------------------------------- | --------------------------------------- |
| `AUTH_REQUIRED`            | Authentication required         | Include valid Authorization header      |
| `INVALID_TOKEN`            | Token is invalid or expired     | Refresh token or re-authenticate        |
| `INSUFFICIENT_PERMISSIONS` | User lacks required permissions | Request access from project owner       |
| `VALIDATION_ERROR`         | Request validation failed       | Check error details for field issues    |
| `NOT_FOUND`                | Resource not found              | Verify resource ID exists               |
| `DUPLICATE_RESOURCE`       | Resource already exists         | Use different identifier                |
| `RATE_LIMITED`             | Too many requests               | Wait and retry with backoff             |
| `QUOTA_EXCEEDED`           | Storage or usage quota exceeded | Upgrade plan or delete unused resources |
| `FILE_TOO_LARGE`           | Upload exceeds size limit       | Compress file or upgrade plan           |
| `UNSUPPORTED_FORMAT`       | File format not supported       | Convert to supported format             |

---

## Specialized Endpoints

For detailed documentation on specialized API endpoints, see the following
guides:

| Documentation                                   | Description                                                             |
| ----------------------------------------------- | ----------------------------------------------------------------------- |
| [3D Generation](./endpoints/3d-generation.md)   | Text-to-3D, image-to-3D, mesh processing, texturing, rigging, animation |
| [Audio](./endpoints/audio.md)                   | Music generation, voice synthesis, sound effects, DAW integration       |
| [Gameplay](./endpoints/gameplay.md)             | Combat simulation, physics, inventory, quests, dialogue, economy        |
| [NPC](./endpoints/npc.md)                       | AI-powered characters, conversations, memory, behavior                  |
| [Creative Tools](./endpoints/creative-tools.md) | Blender, Unreal Engine, Godot, Houdini integration                      |
| [WebSocket](./endpoints/websocket.md)           | Real-time events, progress tracking, collaboration                      |

See the full [Endpoints Reference](./endpoints/README.md) for a complete index.

---

## Further Resources

- [Getting Started Guide](../getting-started/README.md)
- [Architecture Overview](../architecture/README.md)
- [SDK Documentation](./sdk/README.md)
- [Webhook Integration](./webhooks.md)
- [Changelog](./CHANGELOG.md)
