StateSet API Reference

Welcome to the StateSet API. Build powerful autonomous business applications with our comprehensive REST and GraphQL APIs.
Base URL: https://api.stateset.com/v1GraphQL Endpoint: https://api.stateset.com/graphqlWebSocket URL: wss://api.stateset.com/v1/ws

Getting Started

1

Get Your API Key

Sign up at stateset.com and retrieve your API key from the dashboard
2

Choose Your Integration

Select between REST API, GraphQL API, or use our official SDKs
3

Make Your First Call

Test the connection with a simple API call

Authentication

All API requests require authentication using your API key. StateSet supports multiple authentication methods:

API Key Authentication

curl https://api.stateset.com/v1/agents \
  -H "Authorization: Bearer YOUR_API_KEY"

OAuth 2.0 (Coming Soon)

For applications requiring user authorization, OAuth 2.0 support is coming soon.

Rate Limits

Rate Limits by Plan:
  • Starter: 100 requests/minute, 10,000 requests/day
  • Growth: 1,000 requests/minute, 100,000 requests/day
  • Enterprise: Custom limits up to 10,000 requests/minute
Rate limit information is included in response headers:
  • X-RateLimit-Limit: Maximum requests allowed
  • X-RateLimit-Remaining: Requests remaining in current window
  • X-RateLimit-Reset: Unix timestamp when limit resets

Rate Limit Response

When rate limited, you’ll receive a 429 Too Many Requests response:
{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Rate limit exceeded. Please retry after 60 seconds.",
    "retry_after": 60
  }
}

Response Format

All responses follow a consistent format:

Success Response

{
  "success": true,
  "data": {
    // Response data
  },
  "meta": {
    "request_id": "req_abc123",
    "timestamp": "2024-01-15T10:30:00Z",
    "version": "v1",
    "execution_time_ms": 42
  }
}

Error Response

{
  "success": false,
  "error": {
    "code": "RESOURCE_NOT_FOUND",
    "message": "The requested agent does not exist",
    "details": {
      "agent_id": "agent_xyz",
      "suggestion": "Check if the agent ID is correct or create a new agent"
    }
  },
  "meta": {
    "request_id": "req_abc123",
    "timestamp": "2024-01-15T10:30:00Z",
    "documentation_url": "https://docs.stateset.com/errors/RESOURCE_NOT_FOUND"
  }
}

API Versioning

The StateSet API uses URL-based versioning. The current stable version is v1.

Version Lifecycle

VersionStatusSupport Until
v1StableCurrent
v2BetaIn Development

Deprecation Policy

  • Major versions are supported for at least 12 months after deprecation announcement
  • Breaking changes are only introduced in new major versions
  • Deprecation notices are sent via email and included in API responses 90 days before changes

Version Header

You can also specify the API version using the X-API-Version header:
curl https://api.stateset.com/agents \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "X-API-Version: 2024-01-01"

Core Resources

Quick Start Examples

Create an Agent

const agent = await fetch('https://api.stateset.com/v1/agents', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Support Agent',
    role: 'Customer Success Specialist',
    instructions: 'Help customers with their questions',
    capabilities: {
      can_create_tickets: true,
      can_process_returns: true,
      can_issue_refunds: false
    },
    metadata: {
      department: 'customer_support',
      language: 'en'
    }
  })
});

Start a Conversation

const conversation = await fetch('https://api.stateset.com/v1/conversations', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    agent_id: 'agent_123',
    channel: 'web',
    metadata: {
      source: 'website_chat'
    }
  })
});

Send a Message

const message = await fetch('https://api.stateset.com/v1/messages', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    conversation_id: 'conv_456',
    content: 'I need help with my order',
    role: 'user'
  })
});

GraphQL API

For complex queries and real-time subscriptions, use our GraphQL API:
query GetAgentWithConversations($agentId: ID!) {
  agent(id: $agentId) {
    id
    name
    conversations(last: 10) {
      edges {
        node {
          id
          status
          satisfaction_score
          messages {
            content
            role
            timestamp
          }
        }
      }
    }
  }
}

SDKs & Libraries

Official SDKs for popular languages with full TypeScript support:
npm install @stateset/node
# or
yarn add @stateset/node
import { StateSetClient } from '@stateset/node';

const client = new StateSetClient({
  apiKey: process.env.STATESET_API_KEY,
  // Optional: Override default settings
  baseURL: 'https://api.stateset.com/v1',
  timeout: 30000,
  maxRetries: 3
});

// Async/await support
const agent = await client.agents.create({
  name: 'Support Agent',
  role: 'Customer Success'
});

// Promise support
client.agents.list()
  .then(agents => console.log(agents))
  .catch(error => console.error(error));

Webhooks

Receive real-time notifications for events in your StateSet account:

Webhook Configuration

// Configure webhook endpoint
const webhook = await client.webhooks.create({
  url: 'https://your-app.com/webhooks/stateset',
  events: [
    'conversation.started',
    'conversation.escalated',
    'order.created',
    'order.shipped',
    'return.requested',
    'return.approved',
    'return.completed'
  ],
  metadata: {
    environment: 'production'
  }
});

Webhook Security

All webhooks include a signature for verification:
// Verify webhook signatures
const crypto = require('crypto');

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

// In your webhook handler
app.post('/webhooks/stateset', (req, res) => {
  const signature = req.headers['x-stateset-signature'];
  const isValid = verifyWebhookSignature(
    JSON.stringify(req.body),
    signature,
    process.env.WEBHOOK_SECRET
  );
  
  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process webhook...
});

Error Codes

Comprehensive error codes with actionable solutions:
CodeHTTP StatusDescriptionResolution
INVALID_API_KEY401API key is invalid or missingCheck your API key in the dashboard
INSUFFICIENT_PERMISSIONS403API key lacks required permissionsUpgrade plan or adjust key permissions
RESOURCE_NOT_FOUND404Requested resource doesn’t existVerify resource ID and type
VALIDATION_ERROR400Invalid request parametersCheck request body against schema
RATE_LIMITED429Too many requestsImplement exponential backoff
INTERNAL_ERROR500Server errorRetry with exponential backoff
SERVICE_UNAVAILABLE503Temporary service issueCheck status page and retry

Error Handling Best Practices

try {
  const result = await client.agents.create(data);
} catch (error) {
  if (error.code === 'VALIDATION_ERROR') {
    // Handle validation errors
    console.error('Validation failed:', error.details);
  } else if (error.code === 'RATE_LIMITED') {
    // Implement retry logic
    const retryAfter = error.retry_after || 60;
    setTimeout(() => retryRequest(), retryAfter * 1000);
  } else {
    // Handle other errors
    console.error('API error:', error.message);
  }
}

Pagination

List endpoints support cursor-based pagination:
// First page
const page1 = await client.agents.list({ limit: 20 });

// Next page
const page2 = await client.agents.list({ 
  limit: 20,
  cursor: page1.next_cursor 
});

Filtering & Sorting

Most list endpoints support filtering and sorting:
const agents = await client.agents.list({
  filter: {
    status: 'active',
    created_at: { $gte: '2024-01-01' }
  },
  sort: '-created_at', // Descending order
  limit: 50
});

Idempotency

Ensure safe retries with idempotency keys:
const response = await fetch('https://api.stateset.com/v1/orders', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
    'Idempotency-Key': 'unique-request-id-123'
  },
  body: JSON.stringify(orderData)
});
Idempotency keys are stored for 24 hours. Repeated requests with the same key return the original response.

Versioning

The API is versioned via the URL path. We maintain backwards compatibility within major versions. Current version: v1 To use a specific version:
https://api.stateset.com/v1/agents

Support

What’s Next?

Ready to start building? Here are some next steps:
  1. Get your API key from your dashboard
  2. Explore endpoints for your use case
  3. Set up webhooks for real-time updates
  4. Join our Discord for API discussions