Skip to main content

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
For local development:
http://localhost:3000/api/v1

Authentication

All API requests require authentication using Bearer tokens in the Authorization header:
Authorization: Bearer dtk_your_token_here
See Authentication for details on creating and managing API tokens.

Request Format

The API accepts and returns JSON. Always include the Content-Type header for POST/PATCH requests:
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

{
  "workspaces": [...],
  "total": 10
}

Error Response

{
  "error": "Error message"
}

Status Codes

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

Rate Limiting

  • Limit: 100 requests per minute per API token
  • Headers: Rate limit information is included in response headers
See 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}/tokens - Get all tokens

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/{name} - Get a token
  • PATCH /tokensets/{id}/modes/{modeId}/tokens/{name} - Update a token
  • DELETE /tokensets/{id}/modes/{modeId}/tokens/{name} - Delete a token

Export

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

Quick Start

1. Get Your Workspaces

curl -H "Authorization: Bearer YOUR_TOKEN" \
  https://app.tokencraft.dev/api/v1/workspaces

2. Get Tokensets

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

3. Export Tokens

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

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('dtk_your_token_here');
const workspaces = await api.getWorkspaces();

Python

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('dtk_your_token_here')
workspaces = api.get_workspaces()

Best Practices

1. Use Environment Variables

Never hard-code tokens:
export TOKENCRAFT_TOKEN="dtk_your_token_here"
export TOKENCRAFT_API_BASE="https://app.tokencraft.dev/api/v1"

2. Handle Errors

Always check response status:
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:
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:
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