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.
TypeScript / JavaScript
Section titled “TypeScript / JavaScript”Installation
Section titled “Installation”npm install zatabase-js# oryarn add zatabase-js# orpnpm add zatabase-jsRequires Node.js 16 or later.
Initialise the Client
Section titled “Initialise the Client”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 authenticationconst db = new ZatabaseClient({ baseUrl: 'https://your-project.zatabase.io',});
await db.authenticate('admin@example.com', 'SecurePass123!');Execute SQL
Section titled “Execute SQL”// Create a tableawait db.sql.executeSql({ query: 'CREATE TABLE products (name TEXT, price FLOAT, embedding VECTOR(384))',});
// Insert rowsawait db.sql.executeSql({ query: "INSERT INTO products (name, price) VALUES ('Widget', 9.99)",});
// Query dataconst result = await db.sql.executeSql({ query: 'SELECT * FROM products WHERE price < 20',});
console.log(result.rows);Collections
Section titled “Collections”// Create a collection with a projectionawait db.collections.createCollection({ name: 'documents', table_name: 'documents_table', fields: { title: { type: 'text' }, content: { type: 'text' }, embedding: { type: 'vector', dimensions: 768 }, },});
// Ingest dataawait 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 collectionsconst collections = await db.collections.listCollections();console.log(collections);
// Delete a collectionawait db.collections.deleteCollection('documents');Vector Search
Section titled “Vector Search”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 SQLconst 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 searchawait db.sql.executeSql({ query: "CREATE INDEX ON products USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 200)",});// Submit a background jobconst job = await db.jobs.submitJob({ command: ['python', 'train_model.py'], input_data: { dataset: 'v2' },});
// Check statusconst status = await db.jobs.getJob(job.id);console.log(status.status); // "pending" | "running" | "succeeded" | "failed"
// Retrieve logsconst logs = await db.jobs.getJobLogs(job.id);
// List artifactsconst artifacts = await db.jobs.listJobArtifacts(job.id);Health Check
Section titled “Health Check”const isHealthy = await db.healthCheck();console.log(`Server reachable: ${isHealthy}`);Cleanup
Section titled “Cleanup”await db.logout();Python
Section titled “Python”Installation
Section titled “Installation”pip install zatabaseRequires Python 3.8 or later. The SDK uses httpx for async HTTP and pydantic for data validation.
Initialise the Client
Section titled “Initialise the Client”The Python client is async and supports the context manager protocol for automatic cleanup:
import asynciofrom 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)Execute SQL
Section titled “Execute SQL”# Create a tableawait db.execute_sql({ "query": "CREATE TABLE products (name TEXT, price FLOAT, embedding VECTOR(384))"})
# Insert rowsawait db.execute_sql({ "query": "INSERT INTO products (name, price) VALUES ('Widget', 9.99)"})
# Query dataresult = 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"})Collections
Section titled “Collections”# Create a collectionawait db.create_collection({ "name": "documents", "table_name": "documents_table", "fields": { "title": {"type": "text"}, "content": {"type": "text"}, "embedding": {"type": "vector", "dimensions": 768}, },})
# Ingest dataawait 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 collectionscollections = await db.list_collections()print(collections)
# Deleteawait db.delete_collection("documents")Vector Search
Section titled “Vector Search”# Build an HNSW indexawait db.build_hnsw_index({ "table": "documents_table", "column": "embedding", "metric": "cosine", "m": 16, "ef_construction": 200,})
# Approximate nearest-neighbour searchresults = await db.search_hnsw_index({ "table": "documents_table", "column": "embedding", "query": [0.15] * 768, "top_k": 5,})
print(results)
# Exact KNN searchknn = await db.knn_search({ "metric": "cosine", "query": [0.15] * 768, "vectors": [[0.1] * 768, [0.2] * 768], "top_k": 1,})# Submit a jobjob = await db.submit_job({ "command": ["python", "train_model.py"], "input_data": {"dataset": "v2"},})
# Poll for completionimport asyncio
while True: status = await db.get_job(job["id"]) if status["status"] in ("succeeded", "failed", "canceled"): break await asyncio.sleep(1)
# Fetch logslogs = await db.get_job_logs(job["id"])Functions
Section titled “Functions”# Create a serverless functionfunc = await db.create_function({ "name": "process-order", "runtime": "python3.12", "handler": "handler.main", "source": "...",})
# Invoke itresult = await db.invoke_function(func["id"], { "order_id": "ord_123",})Configuration Reference
Section titled “Configuration Reference”Both SDKs accept the same core options:
| Option | TypeScript | Python | Default | Description |
|---|---|---|---|---|
| Base URL | baseUrl | base_url | "zatabase" | Server address. Set to https://your-project.zatabase.io for local dev. |
| API Key | apiKey | api_key | undefined / None | Static API key for authentication. Takes priority over JWT tokens. |
| Timeout | timeout | timeout | 30000 ms / 30.0 s | Request timeout. |
| Retry | retryConfig | retry_config | See below | Retry behaviour for failed requests. |
| Auth | authConfig | auth_config | See below | Token refresh settings. |
Retry Configuration
Section titled “Retry Configuration”| Field | TypeScript | Python | Default | Description |
|---|---|---|---|---|
| Max retries | maxRetries | max_retries | 3 | Number of retry attempts for 5xx and 429 responses. |
| Base delay | baseDelay | base_delay | 1000 ms / 1.0 s | Initial delay before first retry. |
| Max delay | maxDelay | max_delay | 60000 ms / 60.0 s | Upper bound on backoff delay. |
| Backoff | exponentialBackoff | exponential_backoff | true / True | Use exponential backoff (delay * 2^attempt). |
Auth Configuration (TypeScript)
Section titled “Auth Configuration (TypeScript)”| Field | Default | Description |
|---|---|---|
refreshBufferSeconds | 300 | Seconds before expiry to proactively refresh the access token. |
maxRefreshRetries | 3 | Number of refresh attempts before giving up. |
Error Handling
Section titled “Error Handling”TypeScript
Section titled “TypeScript”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); }}Python
Section titled “Python”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}")API Modules
Section titled “API Modules”Both SDKs organise methods into the same set of sub-API modules, accessible as properties on the client:
| Module | TypeScript | Python | Description |
|---|---|---|---|
| SQL | db.sql | db.sql | Execute SQL queries |
| Vectors | db.vectors | db.vectors | KNN search, HNSW index management |
| Collections | db.collections | db.collections | NoSQL document collections |
| Tables | db.tables | db.tables | Table listing and sampling |
| Files | db.files | db.files | Content-addressable file storage |
| Jobs | db.jobs | db.jobs | Background job orchestration |
| Permissions | db.permissions | db.permissions | RBAC permission management |
| Events | db.events | db.events | Event bus publish/subscribe |
| Webhooks | db.webhooks | db.webhooks | Webhook endpoint management |
| Functions | db.functions | db.functions | Serverless function management |
| Analytics | db.analytics | db.analytics | Metrics, insights, anomaly detection |
| Realtime | db.realtime | db.realtime | Real-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.
Additional SDKs
Section titled “Additional SDKs”Zatabase includes a built-in SDK generator (zsdk-generator) that can produce client libraries for additional languages from the OpenAPI specification:
- Go —
zsdk-generator generate --lang go - Rust —
zsdk-generator generate --lang rust - PHP —
zsdk-generator generate --lang php - Java —
zsdk-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.
What’s Next
Section titled “What’s Next”- Quick Start — Get a Zatabase server running and make your first query
- Authentication — JWT flows, API keys, and environment switching
- SQL Reference — Full SQL syntax supported by Zatabase
- Vector Search — Embeddings, HNSW indexes, and similarity queries
- API Reference — Complete REST API documentation