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/v1Authentication
API Key Authentication
The Trae API uses API keys for authentication. Include your API key in the Authorization header:
Authorization: Bearer YOUR_API_KEYObtaining API Keys
- Log in to your Trae dashboard
- Navigate to Settings > API Keys
- Click "Generate New Key"
- Copy and securely store your API key
# Example using curl
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.trae.dev/v1/projectsOAuth 2.0 Authentication
For applications requiring user-specific access, use OAuth 2.0:
Authorization Code Flow
# 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# 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_URIResponse
{
"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:
// 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
GET /projectsParameters:
| Parameter | Type | Description | Default |
|---|---|---|---|
page | integer | Page number | 1 |
limit | integer | Items per page (max 100) | 20 |
sort | string | Sort field (name, created_at, updated_at) | created_at |
order | string | Sort order (asc, desc) | desc |
search | string | Search query | - |
status | string | Filter by status (active, archived) | - |
Example Request:
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.trae.dev/v1/projects?page=1&limit=10&sort=name&order=asc"Response:
{
"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
GET /projects/{project_id}Example Request:
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.trae.dev/v1/projects/proj_1234567890Response:
{
"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
POST /projectsRequest Body:
{
"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:
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/projectsResponse:
{
"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
PUT /projects/{project_id}
PATCH /projects/{project_id}Request Body (PATCH example):
{
"name": "Updated Project Name",
"settings": {
"public": true
}
}Delete Project
DELETE /projects/{project_id}Response:
{
"message": "Project deleted successfully",
"deleted_at": "2024-01-16T16:00:00Z"
}Files
List Files
GET /projects/{project_id}/filesParameters:
| Parameter | Type | Description |
|---|---|---|
path | string | Directory path |
recursive | boolean | Include subdirectories |
type | string | Filter by file type |
Example Request:
curl -H "Authorization: Bearer YOUR_API_KEY" \
"https://api.trae.dev/v1/projects/proj_1234567890/files?path=/src&recursive=true"Response:
{
"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
GET /projects/{project_id}/files/{file_id}/contentResponse:
// 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
PUT /projects/{project_id}/filesRequest Body:
{
"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
DELETE /projects/{project_id}/files/{file_id}Users
Get Current User
GET /userResponse:
{
"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
PATCH /userRequest Body:
{
"name": "John Smith",
"preferences": {
"theme": "light",
"notifications": {
"email": false
}
}
}Collaborations
List Project Collaborators
GET /projects/{project_id}/collaboratorsResponse:
{
"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
POST /projects/{project_id}/collaboratorsRequest Body:
{
"email": "collaborator@example.com",
"role": "editor",
"message": "Join my project!"
}Update Collaborator Role
PATCH /projects/{project_id}/collaborators/{collaborator_id}Request Body:
{
"role": "viewer",
"permissions": ["read", "comment"]
}Remove Collaborator
DELETE /projects/{project_id}/collaborators/{collaborator_id}Templates
List Templates
GET /templatesParameters:
| Parameter | Type | Description |
|---|---|---|
category | string | Filter by category |
language | string | Filter by programming language |
featured | boolean | Show only featured templates |
Response:
{
"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
GET /templates/{template_id}Deployments
List Deployments
GET /projects/{project_id}/deploymentsResponse:
{
"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
POST /projects/{project_id}/deploymentsRequest Body:
{
"environment": "production",
"branch": "main",
"build_command": "npm run build",
"environment_variables": {
"NODE_ENV": "production",
"API_URL": "https://api.example.com"
}
}Get Deployment Logs
GET /projects/{project_id}/deployments/{deployment_id}/logsResponse:
{
"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:
{
"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 Code | Description |
|---|---|
200 | OK - Request successful |
201 | Created - Resource created successfully |
204 | No Content - Request successful, no content returned |
400 | Bad Request - Invalid request data |
401 | Unauthorized - Authentication required |
403 | Forbidden - Insufficient permissions |
404 | Not Found - Resource not found |
409 | Conflict - Resource already exists |
422 | Unprocessable Entity - Validation error |
429 | Too Many Requests - Rate limit exceeded |
500 | Internal Server Error - Server error |
503 | Service Unavailable - Service temporarily unavailable |
Error Codes
| Error Code | Description |
|---|---|
AUTHENTICATION_ERROR | Invalid or missing authentication |
AUTHORIZATION_ERROR | Insufficient permissions |
VALIDATION_ERROR | Request data validation failed |
NOT_FOUND | Requested resource not found |
CONFLICT | Resource already exists |
RATE_LIMIT_EXCEEDED | Too many requests |
INTERNAL_ERROR | Internal server error |
SERVICE_UNAVAILABLE | Service temporarily unavailable |
Rate Limiting
Rate Limit Headers
All API responses include rate limit information:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642348800
X-RateLimit-Window: 3600Rate Limit Tiers
| Plan | Requests per Hour | Burst Limit |
|---|---|---|
| Free | 1,000 | 100 |
| Pro | 10,000 | 500 |
| Enterprise | 100,000 | 2,000 |
Rate Limit Exceeded Response
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Rate limit exceeded",
"details": {
"limit": 1000,
"window": 3600,
"reset_at": "2024-01-16T16:00:00Z"
}
}
}Webhooks
Webhook Events
| Event | Description |
|---|---|
project.created | Project was created |
project.updated | Project was updated |
project.deleted | Project was deleted |
file.created | File was created |
file.updated | File was updated |
file.deleted | File was deleted |
deployment.started | Deployment started |
deployment.completed | Deployment completed |
deployment.failed | Deployment failed |
collaborator.invited | Collaborator was invited |
collaborator.joined | Collaborator joined |
collaborator.removed | Collaborator was removed |
Webhook Payload
{
"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
POST /webhooksRequest Body:
{
"url": "https://your-app.com/webhooks/trae",
"events": ["project.created", "deployment.completed"],
"secret": "your-webhook-secret"
}Webhook Verification
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
npm install @trae/sdk
# or
yarn add @trae/sdkBasic Usage
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
// 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
// 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
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
pip install trae-sdkBasic Usage
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
go get github.com/trae-dev/go-sdkBasic Usage
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
# .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: productionCI/CD Pipeline Integration
// 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
// 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
- Secure API Keys: Store API keys securely and never commit them to version control
- Use Environment Variables: Store sensitive data in environment variables
- Rotate Keys Regularly: Rotate API keys periodically for security
- Scope Permissions: Use the minimum required permissions for each API key
Error Handling
- Handle Rate Limits: Implement exponential backoff for rate limit errors
- Retry Logic: Implement retry logic for transient errors
- Log Errors: Log API errors with request IDs for debugging
- Graceful Degradation: Handle API failures gracefully in your application
Performance
- Use Pagination: Always use pagination for list endpoints
- Cache Responses: Cache API responses when appropriate
- Batch Operations: Use batch operations when available
- Monitor Usage: Monitor your API usage and optimize accordingly
Security
- HTTPS Only: Always use HTTPS for API requests
- Validate Webhooks: Always verify webhook signatures
- Input Validation: Validate all input data before sending to the API
- Audit Logs: Monitor API access logs for suspicious activity