Skip to main content

API Reference

Welcome to the StateBase API reference. This documentation covers all REST endpoints for building production-ready AI agents with state management, memory, and complete audit trails.

Base URL

https://api.statebase.org
All API requests must use HTTPS. HTTP requests will be redirected.

Authentication

StateBase uses API keys for authentication. Include your API key in the X-API-Key header:
curl https://api.statebase.org/v1/sessions \
  -H "X-API-Key: sb_your_api_key_here"

Getting Your API Key

  1. Sign up at app.statebase.org
  2. Navigate to Settings → API Keys
  3. Click Create New Key
  4. Copy and store securely (keys are only shown once)

API Key Format

sb_<24_character_key>
Security: Never commit API keys to version control. Use environment variables:
export STATEBASE_API_KEY="sb_your_key"

SDKs

We provide official SDKs for Python and TypeScript:
pip install statebase

SDK Usage

from statebase import StateBase

sb = StateBase(api_key="sb_your_key")

# Create session
session = sb.sessions.create(
    agent_id="my-agent",
    initial_state={"status": "new"}
)

# Add turn
sb.sessions.add_turn(
    session_id=session.id,
    input={"type": "text", "content": "Hello"},
    output={"type": "text", "content": "Hi there!"}
)

Core Concepts

StateBase is built on four core primitives:

1. Sessions

Containers for agent conversations. Each session has:
  • Unique ID
  • Mutable state (JSON object)
  • TTL (time-to-live)
  • Associated memories and turns
Use case: One session per conversation thread. → Sessions API Reference

2. Turns

Individual interactions between user and agent. Each turn captures:
  • User input
  • Agent output
  • Reasoning (why the agent made this decision)
  • State snapshots (before/after)
Use case: Log every conversation exchange for debugging and analytics. → Turns API Reference

3. Memory

Long-term knowledge that persists across sessions. Memories are:
  • Searchable via semantic similarity
  • Tagged and categorized
  • User-scoped or global
Use case: Store user preferences, facts, and policies. → Memory API Reference

4. Traces

Audit trail of all operations. Every API call creates a trace with:
  • Action type
  • Actor (who made the change)
  • Timestamp
  • Details (what changed)
Use case: Debugging, compliance, and analytics. → Traces API Reference

Request Format

All POST, PATCH, and PUT requests must use JSON:
curl -X POST https://api.statebase.org/v1/sessions \
  -H "X-API-Key: sb_your_key" \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "my-agent"}'

Response Format

All responses are JSON with a consistent structure:

Success Response

{
  "object": "session",
  "id": "sess_abc123",
  "agent_id": "my-agent",
  "created_at": "2026-01-31T04:00:00Z",
  ...
}

List Response

{
  "object": "list",
  "data": [
    { "object": "session", "id": "sess_1", ... },
    { "object": "session", "id": "sess_2", ... }
  ],
  "has_more": false
}

Error Response

{
  "error": {
    "code": "session_not_found",
    "message": "Session sess_abc123 does not exist",
    "type": "invalid_request_error",
    "param": "session_id"
  }
}

Error Codes

HTTP StatusError CodeDescription
400invalid_requestMissing or invalid parameters
401authentication_failedInvalid or missing API key
403permission_deniedAPI key lacks required permissions
404resource_not_foundSession, turn, or memory doesn’t exist
413payload_too_largeRequest body exceeds size limit
429rate_limit_exceededToo many requests (see rate limits below)
500internal_errorServer error (contact support if persists)
503service_unavailableTemporary outage (retry with backoff)

Rate Limits

Rate limits are applied per API key:
TierRequests/MinuteBurst Limit
Free100200
Pro1,0002,000
EnterpriseCustomCustom

Rate Limit Headers

Every response includes rate limit information:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1706745600
HeaderDescription
X-RateLimit-LimitMax requests per minute
X-RateLimit-RemainingRemaining requests in current window
X-RateLimit-ResetUnix timestamp when limit resets

Handling Rate Limits

When you exceed the rate limit, you’ll receive a 429 response:
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Retry after 30 seconds.",
    "type": "rate_limit_error",
    "retry_after": 30
  }
}
Best practice: Implement exponential backoff:
import time

def call_api_with_retry(func, max_retries=3):
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError as e:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # 1s, 2s, 4s
                time.sleep(wait_time)
            else:
                raise

Pagination

List endpoints support cursor-based pagination:
# First page
curl "https://api.statebase.org/v1/sessions?limit=20" \
  -H "X-API-Key: sb_your_key"

# Next page (use last ID from previous response)
curl "https://api.statebase.org/v1/sessions?limit=20&starting_after=sess_xyz789" \
  -H "X-API-Key: sb_your_key"

Pagination Parameters

ParameterTypeDescription
limitintegerMax items per page (default: 20, max: 100)
starting_afterstringID to start after (for next page)

Pagination Response

{
  "object": "list",
  "data": [...],
  "has_more": true,
  "first_id": "sess_abc123",
  "last_id": "sess_xyz789"
}

Idempotency

To safely retry requests without duplicating operations, use idempotency keys:
curl -X POST https://api.statebase.org/v1/sessions \
  -H "X-API-Key: sb_your_key" \
  -H "Idempotency-Key: unique-request-id-123" \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "my-agent"}'
How it works:
  • If request succeeds, response is cached for 24 hours
  • If you retry with same key, cached response is returned
  • No duplicate sessions are created
Supported endpoints: All POST and PATCH endpoints

Webhooks

Subscribe to real-time events:
{
  "url": "https://your-app.com/webhooks/statebase",
  "events": [
    "session.created",
    "session.updated",
    "turn.added",
    "memory.created"
  ]
}
Configure in Dashboard → Webhooks.

Webhook Payload

{
  "id": "evt_abc123",
  "type": "session.created",
  "created_at": "2026-01-31T04:00:00Z",
  "data": {
    "object": "session",
    "id": "sess_xyz789",
    ...
  }
}

Verifying Webhooks

Verify webhook signatures to ensure they’re from StateBase:
import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(expected, signature)

Versioning

The API is versioned via the URL path:
https://api.statebase.org/v1/sessions
                          ^^
                          version
Current version: v1 Breaking changes: We’ll release new versions (v2, v3) for breaking changes. Old versions are supported for 12 months after deprecation.

Data Residency

Choose where your data is stored:
RegionEndpointLocation
USapi.statebase.orgUnited States (default)
EUeu.api.statebase.orgEuropean Union
APACapac.api.statebase.orgAsia-Pacific
Configure in Dashboard → Settings.

Support


Quick Start

Here’s a complete example to get you started:
from statebase import StateBase

# Initialize
sb = StateBase(api_key="sb_your_key")

# Create session
session = sb.sessions.create(
    agent_id="quickstart-agent",
    initial_state={"step": "greeting"}
)

# Add memory
sb.memory.add(
    session_id=session.id,
    content="User prefers concise responses",
    type="preference"
)

# Get context (for agent prompt)
context = sb.sessions.get_context(
    session_id=session.id,
    query="user preferences"
)

# Log conversation turn
sb.sessions.add_turn(
    session_id=session.id,
    input={"type": "text", "content": "Hello"},
    output={"type": "text", "content": "Hi! How can I help?"},
    reasoning="Greeting user"
)

# Update state
sb.sessions.update_state(
    session_id=session.id,
    state={"step": "active"},
    reasoning="User engaged"
)

print(f"Session created: {session.id}")

Next Steps


Ready to build? Start with the Quickstart Guide or explore the Patterns section for production-ready examples.