SDK

Integrate OpenAnalyst into your applications using the official JavaScript/TypeScript and Python SDKs. Full access to analytics, reporting, agents, and data export.

Overview

The OpenAnalyst SDK provides first-class programmatic access to every capability of the platform. Whether you are embedding analytics inside a product, automating report generation, or orchestrating AI agents from your own code, the SDK exposes a clean, consistent interface across JavaScript/TypeScript and Python.

Both SDKs share an identical conceptual model: you initialize a client with your API key, then call methods that map directly to platform features. All network calls are asynchronous, responses are strongly typed, and errors follow a predictable structure that makes them easy to handle and log.

Supported Languages

OpenAnalyst officially maintains and supports two SDK packages:

  • JavaScript / TypeScript — published to npm as @openanalyst/sdk. Ships with full TypeScript type definitions. Compatible with Node.js 18+ and all modern bundlers (Webpack, Vite, esbuild, Rollup).
  • Python — published to PyPI as openanalyst. Requires Python 3.9+. Supports both synchronous and asyncio-based usage via the AsyncClient class.

Community-maintained clients for Ruby, Go, PHP, and Java are listed in the Ecosystem section of this documentation.

Installation

Install the JavaScript/TypeScript SDK using your preferred package manager:

# npm
npm install @openanalyst/sdk

# yarn
yarn add @openanalyst/sdk

# pnpm
pnpm add @openanalyst/sdk

Install the Python SDK from PyPI:

pip install openanalyst

# With optional async support (already included, shown for clarity)
pip install "openanalyst[async]"

Note: The Python package name on PyPI is openanalyst (no hyphen). The import name in code is also openanalyst.

Initialization

All SDK operations require an API key. You can generate and manage API keys from the Settings page inside app.openanalyst.com. Store your key in an environment variable — never hard-code it in source files.

JavaScript / TypeScript

import { OpenAnalyst } from '@openanalyst/sdk';

const client = new OpenAnalyst({
  apiKey: process.env.OPENANALYST_API_KEY,
  // Optional: override the base URL for self-hosted deployments
  baseUrl: 'https://api.openanalyst.com/v1',
  // Optional: default request timeout in milliseconds (default: 30000)
  timeout: 30000,
});

Python (synchronous)

import os
from openanalyst import OpenAnalyst

client = OpenAnalyst(
    api_key=os.environ["OPENANALYST_API_KEY"],
    # Optional overrides
    base_url="https://api.openanalyst.com/v1",
    timeout=30.0,
)

Python (async)

import os
import asyncio
from openanalyst import AsyncOpenAnalyst

async def main():
    client = AsyncOpenAnalyst(api_key=os.environ["OPENANALYST_API_KEY"])
    # ... all methods are awaitable
    datasets = await client.datasets.list()

asyncio.run(main())

Tip: For server-side Next.js, Remix, or Express applications, initialize a single client instance at module scope and reuse it across requests rather than constructing a new client per request.

Core Methods

The SDK client exposes resources as namespaced sub-objects. Each resource corresponds to a category of platform functionality. The table below summarizes the primary resources and their key methods.

ResourceKey MethodsDescription
client.datasetslist(), create(), get(id), delete(id)Manage connected data sources and uploaded datasets
client.queriesrun(params), getResults(id)Execute analytical queries and retrieve results
client.reportslist(), create(), get(id), update(id, patch)Create and manage automated reports
client.agentsrun(params), getSessions(), getSession(id)Trigger and monitor AI agent sessions
client.exportscreate(), download(id)Export data and reports in various formats
client.webhookscreate(), list(), delete(id)Register and manage webhook endpoints

TypeScript Types

The JavaScript SDK ships with comprehensive TypeScript definitions. All request parameter objects and response shapes are exported from the package root, making it straightforward to type your own functions that accept or return SDK objects.

import type {
  Dataset,
  DatasetCreateParams,
  Query,
  QueryRunParams,
  QueryResults,
  Report,
  ReportCreateParams,
  AgentSession,
  AgentRunParams,
  Export,
  Webhook,
  WebhookCreateParams,
  OpenAnalystError,
  RateLimitError,
  AuthenticationError,
  NotFoundError,
} from '@openanalyst/sdk';

// Example: typed helper function
async function createWeeklyReport(
  client: OpenAnalyst,
  params: ReportCreateParams,
): Promise<Report> {
  return client.reports.create(params);
}

Error Handling

All SDK methods throw typed error subclasses derived from OpenAnalystError. This lets you catch specific error categories and respond appropriately.

import {
  OpenAnalyst,
  AuthenticationError,
  RateLimitError,
  NotFoundError,
  OpenAnalystError,
} from '@openanalyst/sdk';

const client = new OpenAnalyst({ apiKey: process.env.OPENANALYST_API_KEY });

try {
  const report = await client.reports.get('rpt_nonexistent');
} catch (err) {
  if (err instanceof AuthenticationError) {
    console.error('Invalid or expired API key');
  } else if (err instanceof RateLimitError) {
    console.error(`Rate limit exceeded. Retry after ${err.retryAfter}s`);
  } else if (err instanceof NotFoundError) {
    console.error('The requested resource was not found');
  } else if (err instanceof OpenAnalystError) {
    console.error(`API error ${err.statusCode}: ${err.message}`);
  } else {
    throw err; // Re-throw unexpected errors
  }
}

In Python, the error hierarchy mirrors the JavaScript SDK:

from openanalyst.exceptions import (
    OpenAnalystError,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
)

try:
    report = client.reports.get("rpt_nonexistent")
except AuthenticationError:
    print("Invalid or expired API key")
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after}s")
except NotFoundError:
    print("Resource not found")
except OpenAnalystError as e:
    print(f"API error {e.status_code}: {e.message}")

Common Operations

Connecting a Data Source

// JavaScript/TypeScript
const dataset = await client.datasets.create({
  name: 'Production Postgres',
  type: 'postgresql',
  connectionString: process.env.DATABASE_URL,
  // Optional: restrict synced tables
  tables: ['orders', 'customers', 'events'],
});

console.log(`Dataset created: ${dataset.id}`);
# Python
dataset = client.datasets.create(
    name="Production Postgres",
    type="postgresql",
    connection_string=os.environ["DATABASE_URL"],
    tables=["orders", "customers", "events"],
)
print(f"Dataset created: {dataset.id}")

Running a Query

// JavaScript/TypeScript
const execution = await client.queries.run({
  datasetId: 'ds_abc123',
  sql: `
    SELECT
      DATE_TRUNC('week', created_at) AS week,
      COUNT(*) AS new_users
    FROM customers
    WHERE created_at >= NOW() - INTERVAL '90 days'
    GROUP BY 1
    ORDER BY 1
  `,
});

// Poll for results (or use webhooks for long-running queries)
const results = await client.queries.getResults(execution.id);
console.log(results.rows); // Array of row objects

Generating a Report

// JavaScript/TypeScript
const report = await client.reports.create({
  name: 'Weekly Executive Summary',
  datasetId: 'ds_abc123',
  schedule: {
    frequency: 'weekly',
    dayOfWeek: 1, // Monday
    hour: 8,
    timezone: 'America/New_York',
  },
  recipients: ['ceo@example.com', 'cto@example.com'],
  format: 'pdf',
  sections: [
    { type: 'kpi', metrics: ['total_revenue', 'active_users', 'churn_rate'] },
    { type: 'chart', chartType: 'line', metric: 'daily_revenue', days: 30 },
    { type: 'table', query: 'SELECT * FROM top_customers LIMIT 10' },
  ],
});

console.log(`Report scheduled: ${report.id}`);

Triggering an AI Agent

// JavaScript/TypeScript
const session = await client.agents.run({
  prompt: 'Analyze revenue trends over the last 90 days and identify the top 3 anomalies.',
  datasetIds: ['ds_abc123'],
  model: 'claude-3-5-sonnet',
  // Stream results as the agent works
  stream: true,
  onMessage: (message) => {
    process.stdout.write(message.content);
  },
});

console.log(`
Agent session complete: ${session.id}`);
console.log(`Final answer: ${session.finalAnswer}`);

Exporting Data

// JavaScript/TypeScript
const exportJob = await client.exports.create({
  datasetId: 'ds_abc123',
  format: 'csv',
  filter: {
    dateRange: { start: '2025-01-01', end: '2025-03-31' },
  },
});

// Wait for the export to be ready, then download
const fileBuffer = await client.exports.download(exportJob.id);
require('fs').writeFileSync('export.csv', fileBuffer);

SDK Versioning

The OpenAnalyst SDK follows semantic versioning. The major version is pinned to the API version it targets: SDK v1.x.x targets API v1. Breaking changes to the API will result in a new major SDK version published alongside the new API version. Minor releases add new capabilities without breaking existing code. Patch releases contain bug fixes only.

You can check the installed SDK version at runtime:

import { VERSION } from '@openanalyst/sdk';
console.log(VERSION); // e.g. "1.4.2"
import openanalyst
print(openanalyst.__version__)  # e.g. "1.4.2"

Warning: SDK major version 0.x releases are considered pre-stable. APIs may change between minor versions. Pin your dependency to a specific patch version in production environments when using 0.x releases.