Skip to content

API Reference ​

This comprehensive API reference provides detailed documentation for all available endpoints, authentication methods, and integration patterns for applications built with Trae.

Overview ​

The Trae API is a RESTful API that provides programmatic access to core platform functionality. This reference covers:

  • Authentication and authorization
  • Core API endpoints
  • Request/response formats
  • Error handling
  • Rate limiting
  • SDK usage
  • Integration examples

Base URL ​

Production: https://api.trae.dev/v1
Staging: https://staging-api.trae.dev/v1
Development: http://localhost:3000/api/v1

Authentication ​

API Key Authentication ​

The Trae API uses API keys for authentication. Include your API key in the Authorization header:

http
Authorization: Bearer YOUR_API_KEY

Obtaining API Keys ​

  1. Log in to your Trae dashboard
  2. Navigate to Settings > API Keys
  3. Click "Generate New Key"
  4. Copy and securely store your API key
bash
# Example using curl
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.trae.dev/v1/projects

OAuth 2.0 Authentication ​

For applications requiring user-specific access, use OAuth 2.0:

Authorization Code Flow ​

http
# Step 1: Authorization Request
GET https://api.trae.dev/oauth/authorize?
  response_type=code&
  client_id=YOUR_CLIENT_ID&
  redirect_uri=YOUR_REDIRECT_URI&
  scope=read:projects write:projects&
  state=RANDOM_STATE_STRING
http
# Step 2: Token Exchange
POST https://api.trae.dev/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&
code=AUTHORIZATION_CODE&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET&
redirect_uri=YOUR_REDIRECT_URI

Response ​

json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "def50200...",
  "scope": "read:projects write:projects"
}

JWT Token Authentication ​

For service-to-service communication:

javascript
// Generate JWT token
const jwt = require('jsonwebtoken');

const payload = {
  iss: 'your-service-id',
  aud: 'trae-api',
  sub: 'service-account',
  exp: Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour
  iat: Math.floor(Date.now() / 1000)
};

const token = jwt.sign(payload, process.env.JWT_SECRET, {
  algorithm: 'HS256'
});

// Use token in requests
const response = await fetch('https://api.trae.dev/v1/projects', {
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

Core Endpoints ​

Projects ​

List Projects ​

http
GET /projects

Parameters:

ParameterTypeDescriptionDefault
pageintegerPage number1
limitintegerItems per page (max 100)20
sortstringSort field (name, created_at, updated_at)created_at
orderstringSort order (asc, desc)desc
searchstringSearch query-
statusstringFilter by status (active, archived)-

Example Request:

bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
     "https://api.trae.dev/v1/projects?page=1&limit=10&sort=name&order=asc"

Response:

json
{
  "data": [
    {
      "id": "proj_1234567890",
      "name": "My Project",
      "description": "A sample project",
      "status": "active",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z",
      "owner": {
        "id": "user_1234567890",
        "name": "John Doe",
        "email": "john@example.com"
      },
      "settings": {
        "public": false,
        "collaboration_enabled": true
      },
      "stats": {
        "files_count": 25,
        "collaborators_count": 3,
        "last_activity": "2024-01-15T09:45:00Z"
      }
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 1,
    "total_pages": 1
  }
}

Get Project ​

http
GET /projects/{project_id}

Example Request:

bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
     https://api.trae.dev/v1/projects/proj_1234567890

Response:

json
{
  "id": "proj_1234567890",
  "name": "My Project",
  "description": "A sample project",
  "status": "active",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z",
  "owner": {
    "id": "user_1234567890",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "collaborators": [
    {
      "id": "user_0987654321",
      "name": "Jane Smith",
      "email": "jane@example.com",
      "role": "editor",
      "joined_at": "2024-01-16T14:20:00Z"
    }
  ],
  "settings": {
    "public": false,
    "collaboration_enabled": true,
    "auto_save": true,
    "version_control": true
  },
  "repository": {
    "url": "https://github.com/user/repo",
    "branch": "main",
    "last_sync": "2024-01-15T09:45:00Z"
  }
}

Create Project ​

http
POST /projects

Request Body:

json
{
  "name": "New Project",
  "description": "Project description",
  "template": "react",
  "settings": {
    "public": false,
    "collaboration_enabled": true
  },
  "repository": {
    "url": "https://github.com/user/repo",
    "branch": "main"
  }
}

Example Request:

bash
curl -X POST \
     -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
       "name": "New Project",
       "description": "A new project",
       "template": "react"
     }' \
     https://api.trae.dev/v1/projects

Response:

json
{
  "id": "proj_2345678901",
  "name": "New Project",
  "description": "A new project",
  "status": "active",
  "created_at": "2024-01-16T15:30:00Z",
  "updated_at": "2024-01-16T15:30:00Z",
  "owner": {
    "id": "user_1234567890",
    "name": "John Doe",
    "email": "john@example.com"
  },
  "settings": {
    "public": false,
    "collaboration_enabled": true,
    "auto_save": true,
    "version_control": true
  }
}

Update Project ​

http
PUT /projects/{project_id}
PATCH /projects/{project_id}

Request Body (PATCH example):

json
{
  "name": "Updated Project Name",
  "settings": {
    "public": true
  }
}

Delete Project ​

http
DELETE /projects/{project_id}

Response:

json
{
  "message": "Project deleted successfully",
  "deleted_at": "2024-01-16T16:00:00Z"
}

Files ​

List Files ​

http
GET /projects/{project_id}/files

Parameters:

ParameterTypeDescription
pathstringDirectory path
recursivebooleanInclude subdirectories
typestringFilter by file type

Example Request:

bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
     "https://api.trae.dev/v1/projects/proj_1234567890/files?path=/src&recursive=true"

Response:

json
{
  "data": [
    {
      "id": "file_1234567890",
      "name": "index.js",
      "path": "/src/index.js",
      "type": "file",
      "size": 1024,
      "mime_type": "application/javascript",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T11:45:00Z",
      "checksum": "sha256:abc123..."
    },
    {
      "id": "dir_1234567890",
      "name": "components",
      "path": "/src/components",
      "type": "directory",
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    }
  ]
}

Get File Content ​

http
GET /projects/{project_id}/files/{file_id}/content

Response:

javascript
// File content returned as text
import React from 'react';

function App() {
  return (
    <div className="App">
      <h1>Hello World</h1>
    </div>
  );
}

export default App;

Create/Update File ​

http
PUT /projects/{project_id}/files

Request Body:

json
{
  "path": "/src/components/Button.js",
  "content": "import React from 'react';\n\nconst Button = ({ children, onClick }) => {\n  return <button onClick={onClick}>{children}</button>;\n};\n\nexport default Button;",
  "encoding": "utf-8"
}

Delete File ​

http
DELETE /projects/{project_id}/files/{file_id}

Users ​

Get Current User ​

http
GET /user

Response:

json
{
  "id": "user_1234567890",
  "name": "John Doe",
  "email": "john@example.com",
  "avatar_url": "https://avatars.example.com/user_1234567890",
  "created_at": "2024-01-01T00:00:00Z",
  "subscription": {
    "plan": "pro",
    "status": "active",
    "expires_at": "2024-12-31T23:59:59Z"
  },
  "preferences": {
    "theme": "dark",
    "language": "en",
    "notifications": {
      "email": true,
      "push": false
    }
  }
}

Update User Profile ​

http
PATCH /user

Request Body:

json
{
  "name": "John Smith",
  "preferences": {
    "theme": "light",
    "notifications": {
      "email": false
    }
  }
}

Collaborations ​

List Project Collaborators ​

http
GET /projects/{project_id}/collaborators

Response:

json
{
  "data": [
    {
      "id": "collab_1234567890",
      "user": {
        "id": "user_0987654321",
        "name": "Jane Smith",
        "email": "jane@example.com",
        "avatar_url": "https://avatars.example.com/user_0987654321"
      },
      "role": "editor",
      "permissions": [
        "read",
        "write",
        "comment"
      ],
      "invited_by": "user_1234567890",
      "invited_at": "2024-01-16T14:00:00Z",
      "joined_at": "2024-01-16T14:20:00Z",
      "status": "active"
    }
  ]
}

Invite Collaborator ​

http
POST /projects/{project_id}/collaborators

Request Body:

json
{
  "email": "collaborator@example.com",
  "role": "editor",
  "message": "Join my project!"
}

Update Collaborator Role ​

http
PATCH /projects/{project_id}/collaborators/{collaborator_id}

Request Body:

json
{
  "role": "viewer",
  "permissions": ["read", "comment"]
}

Remove Collaborator ​

http
DELETE /projects/{project_id}/collaborators/{collaborator_id}

Templates ​

List Templates ​

http
GET /templates

Parameters:

ParameterTypeDescription
categorystringFilter by category
languagestringFilter by programming language
featuredbooleanShow only featured templates

Response:

json
{
  "data": [
    {
      "id": "template_react",
      "name": "React App",
      "description": "Modern React application with TypeScript",
      "category": "frontend",
      "language": "javascript",
      "tags": ["react", "typescript", "vite"],
      "featured": true,
      "author": {
        "name": "Trae Team",
        "url": "https://trae.dev"
      },
      "preview_url": "https://templates.trae.dev/react",
      "repository_url": "https://github.com/trae-dev/template-react",
      "created_at": "2024-01-01T00:00:00Z",
      "updated_at": "2024-01-15T10:00:00Z"
    }
  ]
}

Get Template ​

http
GET /templates/{template_id}

Deployments ​

List Deployments ​

http
GET /projects/{project_id}/deployments

Response:

json
{
  "data": [
    {
      "id": "deploy_1234567890",
      "status": "success",
      "environment": "production",
      "url": "https://my-app.trae.app",
      "commit": {
        "sha": "abc123def456",
        "message": "Add new feature",
        "author": "John Doe"
      },
      "created_at": "2024-01-16T15:00:00Z",
      "completed_at": "2024-01-16T15:05:00Z",
      "duration": 300,
      "logs_url": "https://api.trae.dev/v1/projects/proj_1234567890/deployments/deploy_1234567890/logs"
    }
  ]
}

Create Deployment ​

http
POST /projects/{project_id}/deployments

Request Body:

json
{
  "environment": "production",
  "branch": "main",
  "build_command": "npm run build",
  "environment_variables": {
    "NODE_ENV": "production",
    "API_URL": "https://api.example.com"
  }
}

Get Deployment Logs ​

http
GET /projects/{project_id}/deployments/{deployment_id}/logs

Response:

json
{
  "logs": [
    {
      "timestamp": "2024-01-16T15:00:30Z",
      "level": "info",
      "message": "Starting build process"
    },
    {
      "timestamp": "2024-01-16T15:01:00Z",
      "level": "info",
      "message": "Installing dependencies"
    },
    {
      "timestamp": "2024-01-16T15:04:30Z",
      "level": "info",
      "message": "Build completed successfully"
    },
    {
      "timestamp": "2024-01-16T15:05:00Z",
      "level": "info",
      "message": "Deployment completed"
    }
  ]
}

Error Handling ​

Error Response Format ​

All API errors follow a consistent format:

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request data is invalid",
    "details": [
      {
        "field": "name",
        "message": "Name is required"
      },
      {
        "field": "email",
        "message": "Email must be a valid email address"
      }
    ],
    "request_id": "req_1234567890",
    "timestamp": "2024-01-16T15:30:00Z"
  }
}

HTTP Status Codes ​

Status CodeDescription
200OK - Request successful
201Created - Resource created successfully
204No Content - Request successful, no content returned
400Bad Request - Invalid request data
401Unauthorized - Authentication required
403Forbidden - Insufficient permissions
404Not Found - Resource not found
409Conflict - Resource already exists
422Unprocessable Entity - Validation error
429Too Many Requests - Rate limit exceeded
500Internal Server Error - Server error
503Service Unavailable - Service temporarily unavailable

Error Codes ​

Error CodeDescription
AUTHENTICATION_ERRORInvalid or missing authentication
AUTHORIZATION_ERRORInsufficient permissions
VALIDATION_ERRORRequest data validation failed
NOT_FOUNDRequested resource not found
CONFLICTResource already exists
RATE_LIMIT_EXCEEDEDToo many requests
INTERNAL_ERRORInternal server error
SERVICE_UNAVAILABLEService temporarily unavailable

Rate Limiting ​

Rate Limit Headers ​

All API responses include rate limit information:

http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642348800
X-RateLimit-Window: 3600

Rate Limit Tiers ​

PlanRequests per HourBurst Limit
Free1,000100
Pro10,000500
Enterprise100,0002,000

Rate Limit Exceeded Response ​

json
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded",
    "details": {
      "limit": 1000,
      "window": 3600,
      "reset_at": "2024-01-16T16:00:00Z"
    }
  }
}

Webhooks ​

Webhook Events ​

EventDescription
project.createdProject was created
project.updatedProject was updated
project.deletedProject was deleted
file.createdFile was created
file.updatedFile was updated
file.deletedFile was deleted
deployment.startedDeployment started
deployment.completedDeployment completed
deployment.failedDeployment failed
collaborator.invitedCollaborator was invited
collaborator.joinedCollaborator joined
collaborator.removedCollaborator was removed

Webhook Payload ​

json
{
  "id": "webhook_1234567890",
  "event": "project.created",
  "timestamp": "2024-01-16T15:30:00Z",
  "data": {
    "project": {
      "id": "proj_1234567890",
      "name": "New Project",
      "owner": {
        "id": "user_1234567890",
        "name": "John Doe"
      }
    }
  },
  "delivery_attempt": 1
}

Webhook Configuration ​

http
POST /webhooks

Request Body:

json
{
  "url": "https://your-app.com/webhooks/trae",
  "events": ["project.created", "deployment.completed"],
  "secret": "your-webhook-secret"
}

Webhook Verification ​

javascript
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

// Express.js example
app.post('/webhooks/trae', (req, res) => {
  const signature = req.headers['x-trae-signature'];
  const payload = JSON.stringify(req.body);
  
  if (!verifyWebhook(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Unauthorized');
  }
  
  const { event, data } = req.body;
  
  switch (event) {
    case 'project.created':
      console.log('New project created:', data.project.name);
      break;
    case 'deployment.completed':
      console.log('Deployment completed:', data.deployment.url);
      break;
  }
  
  res.status(200).send('OK');
});

SDK Usage ​

JavaScript/Node.js SDK ​

Installation ​

bash
npm install @trae/sdk
# or
yarn add @trae/sdk

Basic Usage ​

javascript
const { TraeClient } = require('@trae/sdk');

const client = new TraeClient({
  apiKey: process.env.TRAE_API_KEY,
  baseUrl: 'https://api.trae.dev/v1' // optional
});

// List projects
const projects = await client.projects.list({
  page: 1,
  limit: 10
});

// Get project
const project = await client.projects.get('proj_1234567890');

// Create project
const newProject = await client.projects.create({
  name: 'My New Project',
  template: 'react'
});

// Update project
const updatedProject = await client.projects.update('proj_1234567890', {
  name: 'Updated Project Name'
});

// Delete project
await client.projects.delete('proj_1234567890');

File Operations ​

javascript
// List files
const files = await client.files.list('proj_1234567890', {
  path: '/src',
  recursive: true
});

// Get file content
const content = await client.files.getContent('proj_1234567890', 'file_1234567890');

// Create/update file
await client.files.createOrUpdate('proj_1234567890', {
  path: '/src/components/Button.js',
  content: 'import React from "react";\n\nconst Button = () => <button>Click me</button>;\n\nexport default Button;'
});

// Delete file
await client.files.delete('proj_1234567890', 'file_1234567890');

Deployment Operations ​

javascript
// List deployments
const deployments = await client.deployments.list('proj_1234567890');

// Create deployment
const deployment = await client.deployments.create('proj_1234567890', {
  environment: 'production',
  branch: 'main'
});

// Get deployment logs
const logs = await client.deployments.getLogs('proj_1234567890', 'deploy_1234567890');

Error Handling ​

javascript
try {
  const project = await client.projects.get('invalid_id');
} catch (error) {
  if (error instanceof TraeAPIError) {
    console.error('API Error:', error.code, error.message);
    console.error('Details:', error.details);
  } else {
    console.error('Unexpected error:', error);
  }
}

Python SDK ​

Installation ​

bash
pip install trae-sdk

Basic Usage ​

python
from trae_sdk import TraeClient

client = TraeClient(
    api_key=os.environ['TRAE_API_KEY'],
    base_url='https://api.trae.dev/v1'  # optional
)

# List projects
projects = client.projects.list(page=1, limit=10)

# Get project
project = client.projects.get('proj_1234567890')

# Create project
new_project = client.projects.create({
    'name': 'My New Project',
    'template': 'react'
})

# Update project
updated_project = client.projects.update('proj_1234567890', {
    'name': 'Updated Project Name'
})

# Delete project
client.projects.delete('proj_1234567890')

Go SDK ​

Installation ​

bash
go get github.com/trae-dev/go-sdk

Basic Usage ​

go
package main

import (
    "context"
    "log"
    "os"
    
    "github.com/trae-dev/go-sdk/trae"
)

func main() {
    client := trae.NewClient(trae.Config{
        APIKey:  os.Getenv("TRAE_API_KEY"),
        BaseURL: "https://api.trae.dev/v1",
    })
    
    ctx := context.Background()
    
    // List projects
    projects, err := client.Projects.List(ctx, &trae.ProjectListOptions{
        Page:  1,
        Limit: 10,
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Get project
    project, err := client.Projects.Get(ctx, "proj_1234567890")
    if err != nil {
        log.Fatal(err)
    }
    
    // Create project
    newProject, err := client.Projects.Create(ctx, &trae.ProjectCreateRequest{
        Name:     "My New Project",
        Template: "react",
    })
    if err != nil {
        log.Fatal(err)
    }
}

Integration Examples ​

GitHub Actions Integration ​

yaml
# .github/workflows/deploy.yml
name: Deploy to Trae

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Deploy to Trae
        uses: trae-dev/deploy-action@v1
        with:
          api-key: ${{ secrets.TRAE_API_KEY }}
          project-id: ${{ secrets.TRAE_PROJECT_ID }}
          environment: production

CI/CD Pipeline Integration ​

javascript
// deploy.js
const { TraeClient } = require('@trae/sdk');

async function deploy() {
  const client = new TraeClient({
    apiKey: process.env.TRAE_API_KEY
  });
  
  try {
    // Create deployment
    const deployment = await client.deployments.create(process.env.PROJECT_ID, {
      environment: process.env.ENVIRONMENT || 'production',
      branch: process.env.GITHUB_REF_NAME || 'main',
      environment_variables: {
        NODE_ENV: 'production',
        API_URL: process.env.API_URL
      }
    });
    
    console.log(`Deployment started: ${deployment.id}`);
    
    // Poll for completion
    let status = 'pending';
    while (status === 'pending' || status === 'building') {
      await new Promise(resolve => setTimeout(resolve, 5000));
      
      const updated = await client.deployments.get(process.env.PROJECT_ID, deployment.id);
      status = updated.status;
      
      console.log(`Deployment status: ${status}`);
    }
    
    if (status === 'success') {
      console.log(`Deployment successful: ${deployment.url}`);
      process.exit(0);
    } else {
      console.error('Deployment failed');
      process.exit(1);
    }
    
  } catch (error) {
    console.error('Deployment error:', error.message);
    process.exit(1);
  }
}

deploy();

Slack Bot Integration ​

javascript
// slack-bot.js
const { App } = require('@slack/bolt');
const { TraeClient } = require('@trae/sdk');

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET
});

const trae = new TraeClient({
  apiKey: process.env.TRAE_API_KEY
});

// Deploy command
app.command('/deploy', async ({ command, ack, respond }) => {
  await ack();
  
  const [projectId, environment = 'production'] = command.text.split(' ');
  
  if (!projectId) {
    return respond('Usage: /deploy <project-id> [environment]');
  }
  
  try {
    const deployment = await trae.deployments.create(projectId, {
      environment
    });
    
    respond(`🚀 Deployment started for project ${projectId} to ${environment}\nDeployment ID: ${deployment.id}`);
    
  } catch (error) {
    respond(`❌ Deployment failed: ${error.message}`);
  }
});

// List projects command
app.command('/projects', async ({ ack, respond }) => {
  await ack();
  
  try {
    const projects = await trae.projects.list({ limit: 10 });
    
    const projectList = projects.data.map(p => 
      `• ${p.name} (${p.id}) - ${p.status}`
    ).join('\n');
    
    respond(`📁 Your projects:\n${projectList}`);
    
  } catch (error) {
    respond(`❌ Failed to fetch projects: ${error.message}`);
  }
});

app.start(process.env.PORT || 3000);

Best Practices ​

Authentication ​

  1. Secure API Keys: Store API keys securely and never commit them to version control
  2. Use Environment Variables: Store sensitive data in environment variables
  3. Rotate Keys Regularly: Rotate API keys periodically for security
  4. Scope Permissions: Use the minimum required permissions for each API key

Error Handling ​

  1. Handle Rate Limits: Implement exponential backoff for rate limit errors
  2. Retry Logic: Implement retry logic for transient errors
  3. Log Errors: Log API errors with request IDs for debugging
  4. Graceful Degradation: Handle API failures gracefully in your application

Performance ​

  1. Use Pagination: Always use pagination for list endpoints
  2. Cache Responses: Cache API responses when appropriate
  3. Batch Operations: Use batch operations when available
  4. Monitor Usage: Monitor your API usage and optimize accordingly

Security ​

  1. HTTPS Only: Always use HTTPS for API requests
  2. Validate Webhooks: Always verify webhook signatures
  3. Input Validation: Validate all input data before sending to the API
  4. Audit Logs: Monitor API access logs for suspicious activity

Your Ultimate AI-Powered IDE Learning Guide