# Yemaya API Code Examples

This document provides code examples for common API operations in multiple programming languages.

## Table of Contents

- [Authentication](#authentication)
- [Users](#users)
- [Projects](#projects)
- [Assets](#assets)
- [Capability Generation](#capability-generation)
- [Webhooks](#webhooks)

---

## Authentication

### Login

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'your-password',
  }),
});

const data = await response.json();
const accessToken = data.data.accessToken;
const refreshToken = data.data.refreshToken;
```

</details>

<details>
<summary><strong>JavaScript (Axios)</strong></summary>

```javascript
import axios from 'axios';

const { data } = await axios.post('https://api.yemaya.io/v1/auth/login', {
  email: 'user@example.com',
  password: 'your-password',
});

const accessToken = data.data.accessToken;
const refreshToken = data.data.refreshToken;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/auth/login',
    json={
        'email': 'user@example.com',
        'password': 'your-password',
    }
)

data = response.json()
access_token = data['data']['accessToken']
refresh_token = data['data']['refreshToken']
```

</details>

<details>
<summary><strong>Python (httpx - async)</strong></summary>

```python
import httpx

async with httpx.AsyncClient() as client:
    response = await client.post(
        'https://api.yemaya.io/v1/auth/login',
        json={
            'email': 'user@example.com',
            'password': 'your-password',
        }
    )

data = response.json()
access_token = data['data']['accessToken']
```

</details>

<details>
<summary><strong>Go</strong></summary>

```go
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

type LoginRequest struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

type LoginResponse struct {
    Data struct {
        AccessToken  string `json:"accessToken"`
        RefreshToken string `json:"refreshToken"`
    } `json:"data"`
}

func login() (*LoginResponse, error) {
    payload := LoginRequest{
        Email:    "user@example.com",
        Password: "your-password",
    }

    body, _ := json.Marshal(payload)

    resp, err := http.Post(
        "https://api.yemaya.io/v1/auth/login",
        "application/json",
        bytes.NewBuffer(body),
    )
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result LoginResponse
    json.NewDecoder(resp.Body).Decode(&result)
    return &result, nil
}
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "your-password"
  }'
```

</details>

<details>
<summary><strong>Ruby</strong></summary>

```ruby
require 'net/http'
require 'json'

uri = URI('https://api.yemaya.io/v1/auth/login')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri)
request['Content-Type'] = 'application/json'
request.body = {
  email: 'user@example.com',
  password: 'your-password'
}.to_json

response = http.request(request)
data = JSON.parse(response.body)
access_token = data['data']['accessToken']
```

</details>

<details>
<summary><strong>PHP</strong></summary>

```php
<?php

$ch = curl_init('https://api.yemaya.io/v1/auth/login');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode([
        'email' => 'user@example.com',
        'password' => 'your-password',
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
$accessToken = $data['data']['accessToken'];
```

</details>

### Register

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/auth/register', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'newuser@example.com',
    password: 'SecurePassword123!',
    name: 'John Doe',
  }),
});

const data = await response.json();
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/auth/register',
    json={
        'email': 'newuser@example.com',
        'password': 'SecurePassword123!',
        'name': 'John Doe',
    }
)

data = response.json()
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "newuser@example.com",
    "password": "SecurePassword123!",
    "name": "John Doe"
  }'
```

</details>

### Refresh Token

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/auth/refresh', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    refreshToken: 'your-refresh-token',
  }),
});

const data = await response.json();
const newAccessToken = data.data.accessToken;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/auth/refresh',
    json={'refreshToken': 'your-refresh-token'}
)

data = response.json()
new_access_token = data['data']['accessToken']
```

</details>

---

## Users

### Get Current User

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/users/me', {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
});

const data = await response.json();
const user = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.get(
    'https://api.yemaya.io/v1/users/me',
    headers={'Authorization': f'Bearer {access_token}'}
)

user = response.json()['data']
```

</details>

<details>
<summary><strong>Go</strong></summary>

```go
req, _ := http.NewRequest("GET", "https://api.yemaya.io/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+accessToken)

client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()

var result struct {
    Data User `json:"data"`
}
json.NewDecoder(resp.Body).Decode(&result)
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl https://api.yemaya.io/v1/users/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

</details>

### Update User Profile

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/users/me', {
  method: 'PATCH',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Updated Name',
    bio: 'My new bio',
  }),
});

const data = await response.json();
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.patch(
    'https://api.yemaya.io/v1/users/me',
    headers={'Authorization': f'Bearer {access_token}'},
    json={
        'name': 'Updated Name',
        'bio': 'My new bio',
    }
)

updated_user = response.json()['data']
```

</details>

---

## Projects

### List Projects

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/projects?page=1&limit=20', {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
});

const data = await response.json();
const projects = data.data;
const pagination = data.meta;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.get(
    'https://api.yemaya.io/v1/projects',
    headers={'Authorization': f'Bearer {access_token}'},
    params={'page': 1, 'limit': 20}
)

data = response.json()
projects = data['data']
pagination = data['meta']
```

</details>

<details>
<summary><strong>Go</strong></summary>

```go
req, _ := http.NewRequest("GET", "https://api.yemaya.io/v1/projects?page=1&limit=20", nil)
req.Header.Set("Authorization", "Bearer "+accessToken)

client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()

var result struct {
    Data []Project `json:"data"`
    Meta Pagination `json:"meta"`
}
json.NewDecoder(resp.Body).Decode(&result)
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl "https://api.yemaya.io/v1/projects?page=1&limit=20" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

</details>

### Create Project

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/projects', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'My New Project',
    description: 'A film project about adventure',
    type: 'film',
    visibility: 'private',
  }),
});

const data = await response.json();
const project = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/projects',
    headers={'Authorization': f'Bearer {access_token}'},
    json={
        'name': 'My New Project',
        'description': 'A film project about adventure',
        'type': 'film',
        'visibility': 'private',
    }
)

project = response.json()['data']
```

</details>

<details>
<summary><strong>Go</strong></summary>

```go
payload := map[string]interface{}{
    "name":        "My New Project",
    "description": "A film project about adventure",
    "type":        "film",
    "visibility":  "private",
}

body, _ := json.Marshal(payload)

req, _ := http.NewRequest("POST", "https://api.yemaya.io/v1/projects", bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, _ := client.Do(req)
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/projects \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My New Project",
    "description": "A film project about adventure",
    "type": "film",
    "visibility": "private"
  }'
```

</details>

### Get Project

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const projectId = 'proj_abc123';

const response = await fetch(`https://api.yemaya.io/v1/projects/${projectId}`, {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
});

const data = await response.json();
const project = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

project_id = 'proj_abc123'

response = requests.get(
    f'https://api.yemaya.io/v1/projects/{project_id}',
    headers={'Authorization': f'Bearer {access_token}'}
)

project = response.json()['data']
```

</details>

### Update Project

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const projectId = 'proj_abc123';

const response = await fetch(`https://api.yemaya.io/v1/projects/${projectId}`, {
  method: 'PATCH',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Updated Project Name',
    status: 'in_progress',
  }),
});

const data = await response.json();
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

project_id = 'proj_abc123'

response = requests.patch(
    f'https://api.yemaya.io/v1/projects/{project_id}',
    headers={'Authorization': f'Bearer {access_token}'},
    json={
        'name': 'Updated Project Name',
        'status': 'in_progress',
    }
)
```

</details>

### Delete Project

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const projectId = 'proj_abc123';

const response = await fetch(`https://api.yemaya.io/v1/projects/${projectId}`, {
  method: 'DELETE',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
});
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X DELETE https://api.yemaya.io/v1/projects/proj_abc123 \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

</details>

---

## Assets

### Upload Asset

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const projectId = 'proj_abc123';
const file = document.getElementById('fileInput').files[0];

const formData = new FormData();
formData.append('file', file);
formData.append('name', 'My Asset');
formData.append('type', 'image');

const response = await fetch(`https://api.yemaya.io/v1/projects/${projectId}/assets`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
  body: formData,
});

const data = await response.json();
const asset = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

project_id = 'proj_abc123'

with open('my-image.png', 'rb') as f:
    response = requests.post(
        f'https://api.yemaya.io/v1/projects/{project_id}/assets',
        headers={'Authorization': f'Bearer {access_token}'},
        files={'file': ('my-image.png', f, 'image/png')},
        data={
            'name': 'My Asset',
            'type': 'image',
        }
    )

asset = response.json()['data']
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/projects/proj_abc123/assets \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -F "file=@/path/to/image.png" \
  -F "name=My Asset" \
  -F "type=image"
```

</details>

### List Assets

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const projectId = 'proj_abc123';

const response = await fetch(`https://api.yemaya.io/v1/projects/${projectId}/assets`, {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
});

const data = await response.json();
const assets = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

project_id = 'proj_abc123'

response = requests.get(
    f'https://api.yemaya.io/v1/projects/{project_id}/assets',
    headers={'Authorization': f'Bearer {access_token}'}
)

assets = response.json()['data']
```

</details>

---

## Capability Generation

### Start Isis Generation

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/capabilities/isis/generate', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    type: 'text',
    prompt: 'Write a compelling opening scene for a sci-fi thriller',
    model: 'claude-3-opus',
    options: {
      maxTokens: 1000,
      temperature: 0.7,
    },
  }),
});

const data = await response.json();
const generation = data.data;
const generationId = generation.id;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/capabilities/isis/generate',
    headers={'Authorization': f'Bearer {access_token}'},
    json={
        'type': 'text',
        'prompt': 'Write a compelling opening scene for a sci-fi thriller',
        'model': 'claude-3-opus',
        'options': {
            'maxTokens': 1000,
            'temperature': 0.7,
        },
    }
)

generation = response.json()['data']
generation_id = generation['id']
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/capabilities/isis/generate \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "text",
    "prompt": "Write a compelling opening scene for a sci-fi thriller",
    "model": "claude-3-opus",
    "options": {
      "maxTokens": 1000,
      "temperature": 0.7
    }
  }'
```

</details>

### Poll Isis Generation Status

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
async function pollGeneration(generationId: string): Promise<any> {
  while (true) {
    const response = await fetch(`https://api.yemaya.io/v1/capabilities/isis/generations/${generationId}`, {
      headers: {
        'Authorization': `Bearer ${accessToken}`,
      },
    });

    const data = await response.json();
    const status = data.data.status;

    if (status === 'completed') {
      return data.data.result;
    } else if (status === 'failed') {
      throw new Error(data.data.error);
    }

    // Wait 1 second before polling again
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

const result = await pollGeneration(generationId);
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests
import time

def poll_generation(generation_id, access_token):
    while True:
        response = requests.get(
            f'https://api.yemaya.io/v1/capabilities/isis/generations/{generation_id}',
            headers={'Authorization': f'Bearer {access_token}'}
        )

        data = response.json()['data']
        status = data['status']

        if status == 'completed':
            return data['result']
        elif status == 'failed':
            raise Exception(data['error'])

        time.sleep(1)

result = poll_generation(generation_id, access_token)
```

</details>

---

## Webhooks

### Create Webhook

<details>
<summary><strong>JavaScript/TypeScript (Fetch)</strong></summary>

```typescript
const response = await fetch('https://api.yemaya.io/v1/webhooks', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://your-server.com/webhook',
    events: ['project.created', 'project.updated', 'asset.uploaded'],
    secret: 'your-webhook-secret',
  }),
});

const data = await response.json();
const webhook = data.data;
```

</details>

<details>
<summary><strong>Python (requests)</strong></summary>

```python
import requests

response = requests.post(
    'https://api.yemaya.io/v1/webhooks',
    headers={'Authorization': f'Bearer {access_token}'},
    json={
        'url': 'https://your-server.com/webhook',
        'events': ['project.created', 'project.updated', 'asset.uploaded'],
        'secret': 'your-webhook-secret',
    }
)

webhook = response.json()['data']
```

</details>

<details>
<summary><strong>cURL</strong></summary>

```bash
curl -X POST https://api.yemaya.io/v1/webhooks \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhook",
    "events": ["project.created", "project.updated", "asset.uploaded"],
    "secret": "your-webhook-secret"
  }'
```

</details>

### Verify Webhook Signature

<details>
<summary><strong>JavaScript/TypeScript (Node.js)</strong></summary>

```typescript
import crypto from 'crypto';

function verifyWebhookSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expectedSignature}`)
  );
}

// In your webhook handler:
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-yemaya-signature'];
  const isValid = verifyWebhookSignature(
    JSON.stringify(req.body),
    signature,
    'your-webhook-secret'
  );

  if (!isValid) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Process webhook...
  res.json({ received: true });
});
```

</details>

<details>
<summary><strong>Python (Flask)</strong></summary>

```python
import hmac
import hashlib
from flask import Flask, request, jsonify

app = Flask(__name__)

def verify_webhook_signature(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(signature, f'sha256={expected}')

@app.route('/webhook', methods=['POST'])
def webhook():
    signature = request.headers.get('X-Yemaya-Signature')

    if not verify_webhook_signature(
        request.get_data(as_text=True),
        signature,
        'your-webhook-secret'
    ):
        return jsonify({'error': 'Invalid signature'}), 401

    # Process webhook...
    return jsonify({'received': True})
```

</details>

<details>
<summary><strong>Go</strong></summary>

```go
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "io"
    "net/http"
)

func verifyWebhookSignature(payload, signature, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(payload))
    expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))

    return hmac.Equal([]byte(signature), []byte(expected))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    signature := r.Header.Get("X-Yemaya-Signature")
    body, _ := io.ReadAll(r.Body)

    if !verifyWebhookSignature(string(body), signature, "your-webhook-secret") {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    // Process webhook...
    w.Write([]byte(`{"received": true}`))
}
```

</details>

---

## Error Handling

### JavaScript/TypeScript

```typescript
async function apiRequest(url: string, options: RequestInit = {}) {
  const response = await fetch(url, {
    ...options,
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });

  const data = await response.json();

  if (!response.ok) {
    const error = data.error || data;
    throw new Error(`API Error: ${error.code} - ${error.message}`);
  }

  return data;
}

// Usage with error handling
try {
  const project = await apiRequest('https://api.yemaya.io/v1/projects/invalid-id');
} catch (error) {
  console.error('Failed to fetch project:', error.message);
}
```

### Python

```python
import requests

class YemayaAPIError(Exception):
    def __init__(self, code, message, details=None):
        self.code = code
        self.message = message
        self.details = details
        super().__init__(f"{code}: {message}")

def api_request(method, url, **kwargs):
    headers = kwargs.pop('headers', {})
    headers['Authorization'] = f'Bearer {access_token}'

    response = requests.request(method, url, headers=headers, **kwargs)
    data = response.json()

    if not response.ok:
        error = data.get('error', data)
        raise YemayaAPIError(
            error.get('code', 'UNKNOWN'),
            error.get('message', 'Unknown error'),
            error.get('details')
        )

    return data

# Usage with error handling
try:
    project = api_request('GET', 'https://api.yemaya.io/v1/projects/invalid-id')
except YemayaAPIError as e:
    print(f"API Error: {e.code} - {e.message}")
```

---

## Rate Limiting

### Handling Rate Limits (JavaScript)

```typescript
async function apiRequestWithRetry(
  url: string,
  options: RequestInit = {},
  maxRetries = 3
) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const response = await fetch(url, options);

    if (response.status === 429) {
      const retryAfter = response.headers.get('Retry-After') || '1';
      const waitTime = parseInt(retryAfter, 10) * 1000;

      console.log(`Rate limited. Retrying in ${retryAfter}s...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
      continue;
    }

    return response;
  }

  throw new Error('Max retries exceeded');
}
```

### Handling Rate Limits (Python)

```python
import time

def api_request_with_retry(method, url, max_retries=3, **kwargs):
    for attempt in range(max_retries + 1):
        response = requests.request(method, url, **kwargs)

        if response.status_code == 429:
            retry_after = int(response.headers.get('Retry-After', 1))
            print(f"Rate limited. Retrying in {retry_after}s...")
            time.sleep(retry_after)
            continue

        return response

    raise Exception("Max retries exceeded")
```

---

## SDK Usage

For a more streamlined experience, use our official SDKs:

### TypeScript/JavaScript SDK

```bash
npm install @yemaya/sdk
```

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

const client = new YemayaClient({
  apiKey: 'your-api-key',
});

const projects = await client.projects.list();
const newProject = await client.projects.create({
  name: 'My Project',
  type: 'film',
});
```

### Python SDK

```bash
pip install yemaya
```

```python
from yemaya import YemayaClient

client = YemayaClient(api_key='your-api-key')

projects = client.projects.list()
new_project = client.projects.create(
    name='My Project',
    type='film'
)
```

---

## Additional Resources

- [API Reference](/reference) - Interactive API documentation
- [API Playground](/playground) - Test endpoints in your browser
- [Webhook Documentation](./webhooks.md) - Detailed webhook guide
- [OpenAPI Specification](/openapi.json) - Machine-readable API spec
