Skip to content

SDKs

Zatabase provides official SDKs for TypeScript/JavaScript and Python. Both clients cover the full API surface — authentication, SQL execution, collections, vector search, jobs, permissions, events, functions, analytics, and real-time subscriptions. Go, Rust, PHP, and Java SDKs are also available via the built-in SDK generator.

Terminal window
npm install zatabase-js
# or
yarn add zatabase-js
# or
pnpm add zatabase-js

Requires Node.js 16 or later.

import { ZatabaseClient } from 'zatabase-js';
// With an API key (recommended for server-side)
const db = new ZatabaseClient({
baseUrl: 'https://your-project.zatabase.io',
apiKey: 'your-api-key',
});
// Or with email/password authentication
const db = new ZatabaseClient({
baseUrl: 'https://your-project.zatabase.io',
});
await db.authenticate('admin@example.com', 'SecurePass123!');
// Create a table
await db.sql.executeSql({
query: 'CREATE TABLE products (name TEXT, price FLOAT, embedding VECTOR(384))',
});
// Insert rows
await db.sql.executeSql({
query: "INSERT INTO products (name, price) VALUES ('Widget', 9.99)",
});
// Query data
const result = await db.sql.executeSql({
query: 'SELECT * FROM products WHERE price < 20',
});
console.log(result.rows);
// Create a collection with a projection
await db.collections.createCollection({
name: 'documents',
table_name: 'documents_table',
fields: {
title: { type: 'text' },
content: { type: 'text' },
embedding: { type: 'vector', dimensions: 768 },
},
});
// Ingest data
await db.collections.ingestData('documents', {
records: [
{ title: 'First doc', content: 'Hello world', embedding: new Array(768).fill(0.1) },
{ title: 'Second doc', content: 'Goodbye world', embedding: new Array(768).fill(0.2) },
],
});
// List collections
const collections = await db.collections.listCollections();
console.log(collections);
// Delete a collection
await db.collections.deleteCollection('documents');

Zatabase supports exact KNN search via optimized distance kernels and approximate nearest-neighbour search via HNSW indexes. Use SQL for vector queries:

// Exact KNN via SQL
const knnResult = await db.sql.executeSql({
query: `SELECT name, embedding <-> ARRAY[${queryVec.join(',')}] AS distance
FROM products
ORDER BY embedding <-> ARRAY[${queryVec.join(',')}]
LIMIT 10`,
});
// Build an HNSW index for faster approximate search
await db.sql.executeSql({
query: "CREATE INDEX ON products USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 200)",
});
// Submit a background job
const job = await db.jobs.submitJob({
command: ['python', 'train_model.py'],
input_data: { dataset: 'v2' },
});
// Check status
const status = await db.jobs.getJob(job.id);
console.log(status.status); // "pending" | "running" | "succeeded" | "failed"
// Retrieve logs
const logs = await db.jobs.getJobLogs(job.id);
// List artifacts
const artifacts = await db.jobs.listJobArtifacts(job.id);
const isHealthy = await db.healthCheck();
console.log(`Server reachable: ${isHealthy}`);
await db.logout();

Terminal window
pip install zatabase

Requires Python 3.8 or later. The SDK uses httpx for async HTTP and pydantic for data validation.

The Python client is async and supports the context manager protocol for automatic cleanup:

import asyncio
from zatabase import ZatabaseClient
async def main():
# With an API key
async with ZatabaseClient(
base_url="https://your-project.zatabase.io",
api_key="your-api-key",
) as db:
is_healthy = await db.health_check()
print(f"Server reachable: {is_healthy}")
asyncio.run(main())

Or authenticate with email and password:

async with ZatabaseClient(base_url="https://your-project.zatabase.io") as db:
await db.authenticate("admin@example.com", "SecurePass123!")
user = await db.whoami()
print(user)
# Create a table
await db.execute_sql({
"query": "CREATE TABLE products (name TEXT, price FLOAT, embedding VECTOR(384))"
})
# Insert rows
await db.execute_sql({
"query": "INSERT INTO products (name, price) VALUES ('Widget', 9.99)"
})
# Query data
result = await db.execute_sql({
"query": "SELECT * FROM products WHERE price < 20"
})
for row in result["rows"]:
print(row)

The sql sub-API module is also available:

result = await db.sql.execute_sql({"query": "SELECT * FROM products"})
# Create a collection
await db.create_collection({
"name": "documents",
"table_name": "documents_table",
"fields": {
"title": {"type": "text"},
"content": {"type": "text"},
"embedding": {"type": "vector", "dimensions": 768},
},
})
# Ingest data
await db.ingest_data("documents", {
"records": [
{"title": "First doc", "content": "Hello world", "embedding": [0.1] * 768},
{"title": "Second doc", "content": "Goodbye world", "embedding": [0.2] * 768},
]
})
# List collections
collections = await db.list_collections()
print(collections)
# Delete
await db.delete_collection("documents")
# Build an HNSW index
await db.build_hnsw_index({
"table": "documents_table",
"column": "embedding",
"metric": "cosine",
"m": 16,
"ef_construction": 200,
})
# Approximate nearest-neighbour search
results = await db.search_hnsw_index({
"table": "documents_table",
"column": "embedding",
"query": [0.15] * 768,
"top_k": 5,
})
print(results)
# Exact KNN search
knn = await db.knn_search({
"metric": "cosine",
"query": [0.15] * 768,
"vectors": [[0.1] * 768, [0.2] * 768],
"top_k": 1,
})
# Submit a job
job = await db.submit_job({
"command": ["python", "train_model.py"],
"input_data": {"dataset": "v2"},
})
# Poll for completion
import asyncio
while True:
status = await db.get_job(job["id"])
if status["status"] in ("succeeded", "failed", "canceled"):
break
await asyncio.sleep(1)
# Fetch logs
logs = await db.get_job_logs(job["id"])
# Create a serverless function
func = await db.create_function({
"name": "process-order",
"runtime": "python3.12",
"handler": "handler.main",
"source": "...",
})
# Invoke it
result = await db.invoke_function(func["id"], {
"order_id": "ord_123",
})

Both SDKs accept the same core options:

OptionTypeScriptPythonDefaultDescription
Base URLbaseUrlbase_url"zatabase"Server address. Set to https://your-project.zatabase.io for local dev.
API KeyapiKeyapi_keyundefined / NoneStatic API key for authentication. Takes priority over JWT tokens.
Timeouttimeouttimeout30000 ms / 30.0 sRequest timeout.
RetryretryConfigretry_configSee belowRetry behaviour for failed requests.
AuthauthConfigauth_configSee belowToken refresh settings.
FieldTypeScriptPythonDefaultDescription
Max retriesmaxRetriesmax_retries3Number of retry attempts for 5xx and 429 responses.
Base delaybaseDelaybase_delay1000 ms / 1.0 sInitial delay before first retry.
Max delaymaxDelaymax_delay60000 ms / 60.0 sUpper bound on backoff delay.
BackoffexponentialBackoffexponential_backofftrue / TrueUse exponential backoff (delay * 2^attempt).
FieldDefaultDescription
refreshBufferSeconds300Seconds before expiry to proactively refresh the access token.
maxRefreshRetries3Number of refresh attempts before giving up.

The TypeScript SDK throws standard Axios errors. Wrap calls in try/catch:

import { AxiosError } from 'axios';
try {
await db.sql.executeSql({ query: 'SELECT * FROM nonexistent' });
} catch (error) {
if (error instanceof AxiosError) {
console.error(`HTTP ${error.response?.status}: ${error.response?.data}`);
} else {
console.error('Unexpected error:', error);
}
}

The Python SDK provides a structured exception hierarchy:

from zatabase.exceptions import (
ZatabaseError, # Base exception
AuthenticationError, # 401 / credential issues
ValidationError, # Invalid input
APIError, # General API error (has .status_code)
RateLimitError, # 429 Too Many Requests
NotFoundError, # 404
PermissionError, # 403
)
try:
await db.execute_sql({"query": "SELECT * FROM nonexistent"})
except NotFoundError:
print("Table does not exist")
except RateLimitError:
print("Slow down -- retry after backoff")
except APIError as e:
print(f"API error {e.status_code}: {e}")
except ZatabaseError as e:
print(f"SDK error: {e}")

Both SDKs organise methods into the same set of sub-API modules, accessible as properties on the client:

ModuleTypeScriptPythonDescription
SQLdb.sqldb.sqlExecute SQL queries
Vectorsdb.vectorsdb.vectorsKNN search, HNSW index management
Collectionsdb.collectionsdb.collectionsNoSQL document collections
Tablesdb.tablesdb.tablesTable listing and sampling
Filesdb.filesdb.filesContent-addressable file storage
Jobsdb.jobsdb.jobsBackground job orchestration
Permissionsdb.permissionsdb.permissionsRBAC permission management
Eventsdb.eventsdb.eventsEvent bus publish/subscribe
Webhooksdb.webhooksdb.webhooksWebhook endpoint management
Functionsdb.functionsdb.functionsServerless function management
Analyticsdb.analyticsdb.analyticsMetrics, insights, anomaly detection
Realtimedb.realtimedb.realtimeReal-time subscriptions

The Python client also exposes top-level convenience methods (e.g. db.execute_sql(), db.list_collections(), db.knn_search()) that call the same underlying endpoints without going through the sub-module.


Zatabase includes a built-in SDK generator (zsdk-generator) that can produce client libraries for additional languages from the OpenAPI specification:

  • Gozsdk-generator generate --lang go
  • Rustzsdk-generator generate --lang rust
  • PHPzsdk-generator generate --lang php
  • Javazsdk-generator generate --lang java

The generated SDKs follow the same structure: a client class with sub-API modules, authentication management, retry logic, and typed models.