> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokencraft.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# API Introduction

> Getting started with the Tokencraft REST API

# Tokencraft REST API

The Tokencraft API is a RESTful API that provides programmatic access to your design tokens. Use it to integrate Tokencraft into your build process, CI/CD pipeline, or any application.

## Base URL

```
https://app.tokencraft.dev/api/v1
```

<Note>
  Session-authenticated dashboard endpoints are available under `https://app.tokencraft.dev/api` (for example workspace collaboration and organization environments). This page focuses on the API-token surface under `/api/v1`.
</Note>

## Authentication

All API requests require authentication using Bearer tokens in the Authorization header:

```bash theme={null}
Authorization: Bearer tkc_your_token_here
```

See [Authentication](/authentication) for details on creating and managing API tokens.

## API v1 Access Model

API v1 access is scoped by token + workspace access context:

* `read:tokens` is required for read endpoints.
* `write:tokens` is required for create/update/delete endpoints.
* `export:tokens` is required for export endpoints.

Write authorization is evaluated on the target workspace:

* If the workspace belongs to an organisation on **Business**:
  * read: `owner`, `admin`, `editor`, `viewer`
  * write: `owner`, `admin`, `editor` (viewer seats are read-only)
  * `viewer` write attempts return `403`
* If the workspace is a solo workspace (FREE or PRO owner):
  * read/write remain owner-only
* If the workspace owner plan does not include API write access (for example `FREE`), write endpoints return `403` even with `write:tokens` scope.

For security, inaccessible resources return `404` on workspace-scoped routes.

## Request Format

The API accepts and returns JSON. Always include the `Content-Type` header for POST/PATCH requests:

```bash theme={null}
curl -X POST https://app.tokencraft.dev/api/v1/workspaces \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"My Workspace"}'
```

## Response Format

### Success Response

```json theme={null}
{
  "workspaces": [...],
  "total": 10
}
```

### Error Response

```json theme={null}
{
  "error": "Error message"
}
```

## Status Codes

| Code  | Description                             |
| ----- | --------------------------------------- |
| `200` | Success                                 |
| `201` | Created                                 |
| `400` | Bad Request - Invalid input             |
| `401` | Unauthorized - Invalid or missing token |
| `404` | Not Found - Resource doesn't exist      |
| `429` | Too Many Requests - Rate limit exceeded |
| `500` | Internal Server Error                   |

## Rate Limiting

* **Limit**: 100 requests per minute per API token
* **Headers**: Rate limit information is included in response headers

See [Rate Limits](/api-reference/rate-limits) for details.

## Endpoints Overview

### Workspaces

* `GET /workspaces` - List all workspaces
* `POST /workspaces` - Create a workspace
* `GET /workspaces/{id}` - Get a workspace
* `PATCH /workspaces/{id}` - Update a workspace
* `DELETE /workspaces/{id}` - Delete a workspace
* `GET /workspaces/{id}/tokensets` - List tokensets in a workspace

### Tokensets

* `GET /tokensets/{id}` - Get a tokenset
* `PATCH /tokensets/{id}` - Update a tokenset
* `DELETE /tokensets/{id}` - Delete a tokenset
* `GET /tokensets/{id}/modes` - List modes
* `POST /tokensets/{id}/modes` - Create a mode
* `GET /tokensets/{id}/modes/{modeId}` - Get a mode
* `PATCH /tokensets/{id}/modes/{modeId}` - Update a mode
* `DELETE /tokensets/{id}/modes/{modeId}` - Delete a mode
* `GET /tokensets/{id}/tokens` - Get all tokens (across all modes)

### Tokens

* `GET /tokensets/{id}/modes/{modeId}/tokens` - List tokens in a mode
* `POST /tokensets/{id}/modes/{modeId}/tokens` - Create a token
* `GET /tokensets/{id}/modes/{modeId}/tokens/{tokenId}` - Get a token by ID
* `PATCH /tokensets/{id}/modes/{modeId}/tokens/{tokenId}` - Update a token
* `DELETE /tokensets/{id}/modes/{modeId}/tokens/{tokenId}` - Delete a token

### Export

* `GET /tokensets/{id}/export` - Export all modes
* `GET /tokensets/{id}/modes/{modeId}/export` - Export a specific mode

### Dashboard Session Endpoints (`/api`, cookie auth)

* `GET /api/subscription/downgrade-status` - Get downgrade overage/enforcement status
* `POST /api/workspaces` - Create workspace from dashboard session
* `GET /api/workspaces/{workspaceId}/members` - List workspace members
* `POST /api/workspaces/{workspaceId}/members` - Add/update member immediately (no pending invitation email)
* `POST /api/workspaces/invitations/accept` - Deprecated, returns `410 Gone`
* `GET /api/workspaces/invitations/verify` - Deprecated, returns `410 Gone`
* `DELETE /api/workspaces/invitations/{id}` - Deprecated, returns `410 Gone`

### Organizations & Environments (Business Session API)

* `GET /api/organizations/{orgId}/environments` - List organization environments
* `POST /api/organizations/{orgId}/environments` - Create environment
* `DELETE /api/organizations/{orgId}/environments/{environmentId}` - Delete non-production environment
* `GET /api/organizations/{orgId}/environments/{environmentId}/releases` - List releases
* `POST /api/organizations/{orgId}/environments/{environmentId}/releases` - Publish release
* `POST /api/organizations/{orgId}/environments/{environmentId}/merge` - Merge a source environment into `Production`
* `GET /api/organizations/{orgId}/environments/{environmentId}/export` - Export active environment release

## Quick Start

### 1. Get Your Workspaces

```bash theme={null}
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://app.tokencraft.dev/api/v1/workspaces
```

### 2. Get Tokensets

```bash theme={null}
curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://app.tokencraft.dev/api/v1/workspaces/{workspace_id}/tokensets
```

### 3. Export Tokens

```bash theme={null}
curl -H "Authorization: Bearer YOUR_TOKEN" \
  "https://app.tokencraft.dev/api/v1/tokensets/{tokenset_id}/modes/{mode_id}/export?format=css"
```

## SDKs and Libraries

### JavaScript/TypeScript

```javascript theme={null}
class TokencraftAPI {
  constructor(token) {
    this.token = token;
    this.baseUrl = 'https://app.tokencraft.dev/api/v1';
  }

  async getWorkspaces() {
    const response = await fetch(`${this.baseUrl}/workspaces`, {
      headers: { 'Authorization': `Bearer ${this.token}` }
    });
    return response.json();
  }

  async exportTokens(tokensetId, modeId, format = 'json') {
    const response = await fetch(
      `${this.baseUrl}/tokensets/${tokensetId}/modes/${modeId}/export?format=${format}`,
      { headers: { 'Authorization': `Bearer ${this.token}` } }
    );
    return response.text();
  }
}

// Usage
const api = new TokencraftAPI('tkc_your_token_here');
const workspaces = await api.getWorkspaces();
```

### Python

```python theme={null}
import requests

class TokencraftAPI:
    def __init__(self, token):
        self.token = token
        self.base_url = 'https://app.tokencraft.dev/api/v1'
        self.headers = {'Authorization': f'Bearer {token}'}
    
    def get_workspaces(self):
        response = requests.get(
            f'{self.base_url}/workspaces',
            headers=self.headers
        )
        return response.json()
    
    def export_tokens(self, tokenset_id, mode_id, format='json'):
        response = requests.get(
            f'{self.base_url}/tokensets/{tokenset_id}/modes/{mode_id}/export',
            params={'format': format},
            headers=self.headers
        )
        return response.text

# Usage
api = TokencraftAPI('tkc_your_token_here')
workspaces = api.get_workspaces()
```

## Best Practices

### 1. Use Environment Variables

Never hard-code tokens:

```bash theme={null}
export TOKENCRAFT_TOKEN="tkc_your_token_here"
```

### 2. Handle Errors

Always check response status:

```javascript theme={null}
const response = await fetch(url, { headers });

if (!response.ok) {
  const error = await response.json();
  throw new Error(error.error || 'API request failed');
}

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

### 3. Respect Rate Limits

Implement exponential backoff for 429 responses:

```javascript theme={null}
async function fetchWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    const response = await fetch(url, options);
    
    if (response.status !== 429) {
      return response;
    }
    
    // Wait before retrying (exponential backoff)
    await new Promise(resolve => 
      setTimeout(resolve, Math.pow(2, i) * 1000)
    );
  }
  
  throw new Error('Max retries exceeded');
}
```

### 4. Cache Responses

Design tokens don't change frequently:

```javascript theme={null}
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

async function getCachedTokens(tokensetId, modeId) {
  const cacheKey = `${tokensetId}-${modeId}`;
  const cached = cache.get(cacheKey);
  
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }
  
  const data = await fetchTokens(tokensetId, modeId);
  cache.set(cacheKey, { data, timestamp: Date.now() });
  
  return data;
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication">
    Learn about API authentication
  </Card>

  <Card title="Workspaces" icon="folder" href="/api-reference/workspaces/list">
    Manage workspaces
  </Card>

  <Card title="Export" icon="file-export" href="/api-reference/export/mode">
    Export tokens in multiple formats
  </Card>

  <Card title="Errors" icon="triangle-exclamation" href="/api-reference/errors">
    Handle errors properly
  </Card>
</CardGroup>
