Docs/Reference/Dokwe DB API

Dokwe DB API

9 min read
On this page

This is the reference for the Dokwe platform API that manages a Dokwe DB project. Once a project is provisioned, end-user traffic (CRUD on tables, auth flows, realtime subscriptions) flows directly to the bundled PostgREST / GoTrue / Realtime containers — see §24 for pointers into those upstream APIs.

1. Conventions#

Base URL#

code
https://<your-dokwe-host>/api

For the hosted version that's https://dokwe.com/api. For self-hosted Dokwe deployments, use whatever you set as app.baseDomain. Every endpoint in this document is relative to that base URL.

Authentication#

Every endpoint listed here requires a Dokwe platform JWT in the Authorization header:

http
Authorization: Bearer <your-dokwe-platform-jwt>

The two endpoints that override this — …/storage/public/…/object and …/storage/signed/…/object — are explicitly callable without a header (see §20).

Project ID#

Most routes are nested under /dokwe-db/:id/.... The :id is the project's UUID, returned from POST /dokwe-db or visible at the top of the dokwe-db detail page in the dashboard.

Errors#

Errors follow Nest's default HttpException shape:

json
{
  "statusCode": 400,
  "message": "Bucket name must be 3–120 chars …",
  "error": "Bad Request"
}

Where the message can also be an array of validation errors when a DTO fails:

json
{ "statusCode": 400, "message": ["name should not be empty"], "error": "Bad Request" }

Pagination#

Endpoints that paginate accept ?page= (1-indexed) and ?perPage=. The default page size is 50 and is capped per-endpoint (often 100, sometimes 500 for row reads).

Rate limits#

Rate limiting is not enforced inside the platform API. To rate-limit the auto-generated PostgREST endpoints, configure the connection-pool size on the API tab (see §23) or place a reverse proxy in front.


2. Project lifecycle#

GET /dokwe-db/check-slug#

Real-time slug availability check used by the create form.

QueryDescription
slugCandidate slug (/^[a-z0-9-]+$/)

Response

json
{ "available": true }

POST /dokwe-db#

Create a new project. Provisioning runs asynchronously — the response returns immediately with status: "provisioning"; poll GET /dokwe-db/:id for state changes.

Body — CreateDokweDbDto

ts
{
  name: string;          // 2..120 chars
  slug?: string;         // 2..60, /^[a-z0-9-]+$/, auto-generated if omitted
  serverId?: string;     // UUID of a connected BYOS server, or omit for Dokwe-managed
  dbName?: string;       // optional Postgres database name (defaults to slug.replace(/-/g, '_'))
}

Response — DokweDbProject

ts
{
  id: string;
  name: string;
  slug: string;
  region: string;
  status: 'provisioning' | 'running' | 'stopped' | 'error' | 'deleted';
  postgrestPort: number;
  postgrestStatus: 'stopped' | 'running' | 'error';
  realtimePort: number | null;
  realtimeStatus: 'stopped' | 'provisioning' | 'running' | 'error';
  gotruePort: number | null;
  gotrueStatus: 'stopped' | 'running' | 'error';
  // …
}

GET /dokwe-db#

List all projects in the caller's workspace.

Response — DokweDbProject[]

GET /dokwe-db/:id#

Get a single project. Includes the resolved postgrestUrl so clients don't have to compute it.

DELETE /dokwe-db/:id#

Tear down everything: stop containers, drop the volume, free the slug. Irreversible.


3. API keys & JWT#

Every project has three JWTs signed with a project-scoped secret:

KeyRoleUse
anon_keyanonclient-side; constrained by RLS
service_roleservice_roleserver-side; bypasses RLS
jwt_secret—the HS256 signing secret (server-side only)

GET /dokwe-db/:id/api-keys#

Returns the three keys (encrypted at rest, decrypted on read). Don't expose service_role or jwt_secret to the browser.

json
{ "anonKey": "eyJ...", "serviceKey": "eyJ...", "jwtSecret": "abc..." }

POST /dokwe-db/:id/api-keys/reveal#

Same payload as the GET — kept as a separate POST so dashboards can gate the action behind a confirmation step.

POST /dokwe-db/:id/api-keys/rotate#

Generates a fresh jwt_secret and re-signs the two JWTs. Old keys stop working immediately, so update your clients before rotating.

json
{ "anonKey": "eyJ...", "serviceKey": "eyJ...", "jwtSecret": "new-secret" }

4. Tables (DDL)#

GET /dokwe-db/:id/tables#

List every table in the public schema with its columns, RLS state, and foreign-key relationships.

Response — TableDefinition[]

ts
{
  name: string;
  schema: 'public';
  rowEstimate: number;
  rlsEnabled: boolean;
  rlsForced: boolean;
  columns: ColumnDefinition[];
}

interface ColumnDefinition {
  name: string;
  type: string;             // information_schema data_type
  nullable: boolean;
  default: string | null;
  isPrimaryKey: boolean;
  isUnique: boolean;
  isIdentity: boolean;
  foreignKey: { table: string; column: string } | null;
}

POST /dokwe-db/:id/tables#

Create a table.

Body — CreateTableDto

ts
{
  name: string;
  columns: Array<{
    name: string;
    type: string;          // validated against an allow-list (text, uuid, int4, jsonb, vector(n), …)
    nullable?: boolean;
    default?: string | null;
    primaryKey?: boolean;
    unique?: boolean;
    references?: { table: string; column: string };
  }>;
}

DELETE /dokwe-db/:id/tables/:name#

Drop the table (CASCADE).


5. Columns (DDL)#

POST /dokwe-db/:id/tables/:name/columns#

Add a column. Body is one of CreateTableDto.columns[number].

PATCH /dokwe-db/:id/tables/:name/columns/:col#

Alter the column. Body — AlterColumnDto:

ts
{
  newName?: string;
  type?: string;
  nullable?: boolean;
  default?: string | null;
}

Type changes use USING ::<newType> and may fail on incompatible data.

DELETE /dokwe-db/:id/tables/:name/columns/:col#

Drop the column.


6. Rows (data)#

GET /dokwe-db/:id/tables/:name/rows#

Read rows with filter / sort / pagination.

QueryDescription
page1-indexed, default 1
limitdefault 50, capped at 500
sortcolumn name
orderasc or desc
filtersJSON-encoded array, see below

filters is an array of { column, op, value } where op is one of: eq, neq, gt, gte, lt, lte, like, ilike, is, in.

Response

json
{
  "rows": [...],
  "columns": ["id", "title", "completed"],
  "totalRows": 1234,
  "page": 1,
  "limit": 50
}

POST /dokwe-db/:id/tables/:name/rows#

Insert one or more rows.

json
{ "rows": [ { "title": "Buy milk" }, { "title": "Walk dog" } ] }

PATCH /dokwe-db/:id/tables/:name/rows#

Update rows matching a filter set.

json
{ "set": { "completed": true }, "filters": [{ "column": "id", "op": "eq", "value": 1 }] }

DELETE /dokwe-db/:id/tables/:name/rows#

Delete rows matching a filter set.

json
{ "filters": [{ "column": "id", "op": "eq", "value": 1 }] }

7. CSV import & export#

GET /dokwe-db/:id/tables/:name/export.csv#

Streams up to 100 000 rows as RFC 4180 CSV.

http
HTTP/1.1 200 OK
Content-Type: text/csv; charset=utf-8
Content-Disposition: attachment; filename="todos.csv"

POST /dokwe-db/:id/tables/:name/import.csv#

json
{ "csv": "id,title,completed\n1,Buy milk,false\n…" }

Response

json
{ "inserted": 482, "skipped": 0, "errors": [] }

The first row is the header; column names must match the table. Width- mismatched rows are skipped (counted under skipped); failed batches record an errors[] entry but don't abort the run.


8. Raw SQL#

POST /dokwe-db/:id/sql#

Execute an arbitrary SQL statement.

json
{ "sql": "SELECT count(*) FROM users WHERE created_at > now() - interval '7 days'" }

Response

json
{
  "columns": ["count"],
  "rows": [{ "count": 42 }],
  "rowCount": 1,
  "duration": 12
}

9. Schema dump & apply#

These pair with the dokwe db pull / db push CLI commands.

GET /dokwe-db/:id/schema/dump#

Returns a pg_dump --schema-only-ish blob for the public schema as plain text. Includes tables, indexes, constraints, and policies.

POST /dokwe-db/:id/schema/apply#

json
{ "sql": "CREATE TABLE …; ALTER TABLE …; CREATE POLICY …;" }

Response

json
{ "success": true }

On failure: { "success": false, "error": "syntax error at or near …" }.


10. Types#

GET /dokwe-db/:id/types#

Returns a single TypeScript file with a Database type covering every table in the public schema. Drop into your client codebase or pipe through the CLI:

sh
dokwe db types > src/database.types.ts

11. Row Level Security policies#

GET /dokwe-db/:id/policies#

ts
Array<{
  name: string;
  table: string;
  schema: 'public';
  command: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL';
  permissive: boolean;
  roles: string[];
  using: string | null;
  check: string | null;
}>

POST /dokwe-db/:id/policies#

Body — CreatePolicyDto

ts
{
  table: string;
  name: string;
  command: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'ALL';
  role?: 'anon' | 'authenticated' | 'service_role';
  using?: string;          // boolean expression
  check?: string;          // boolean expression for INSERT/UPDATE
}

DELETE /dokwe-db/:id/policies/:name#

QueryDescription
tablerequired — disambiguates policy names that collide across tables

POST /dokwe-db/:id/tables/:name/rls#

Toggle Row Level Security.

json
{ "action": "enable" }   // or "disable"

POST /dokwe-db/:id/tables/:name/test-policy#

Run a SELECT count(*) against the table impersonating a role + JWT subject. The transaction always rolls back; nothing is mutated.

json
{ "role": "authenticated", "uid": "00000000-0000-0000-0000-000000000abc" }

Response

json
{ "ok": true, "visibleRows": 7 }

Or, if a policy denies it:

json
{ "ok": false, "visibleRows": 0, "error": "permission denied for table todos" }

12. Authentication — service control#

GoTrue runs as a sidecar container per project; the routes in this section control its lifecycle. End-user signup / login flows hit the GoTrue HTTP API directly — see §24.

POST /dokwe-db/:id/auth/enable#

Provision the GoTrue container, allocate a port, run schema migrations in the user's Postgres. Idempotent.

POST /dokwe-db/:id/auth/disable#

Stop + remove the container. Existing users in the auth.users table remain — re-enable to bring them back online.

GET /dokwe-db/:id/auth/status#

json
{
  "status": "running",
  "gotrueUrl": "http://your-host:60001",
  "siteUrl": "https://app.example.com",
  "failReason": null
}

GET /dokwe-db/:id/auth/config#

The full saved auth config (without secrets):

ts
{
  siteUrl: string | null;
  smtp: { host: string; port: number; user: string; from: string } | null;
  oauth: Record<string, { enabled: boolean; clientId: string }>;
  security: {
    passwordMinLength?: number;
    requireEmailConfirm?: boolean;
    accessTokenTtl?: number;
    allowedRedirectUrls?: string[];
  };
  sms: { provider: 'twilio'; accountSid: string; messageServiceSid: string; from?: string } | null;
}

POST /dokwe-db/:id/auth/site-url#

json
{ "url": "https://app.example.com" }

Used for the redirect_to defaults in confirmation / magic-link emails.


13. Authentication — email & SMS#

POST /dokwe-db/:id/auth/email#

Configure either SendPipe or custom SMTP.

SendPipe (recommended on the hosted version):

json
{
  "provider": "sendpipe",
  "from": "no-reply@example.com",
  "sendpipeApiKey": "...",
  "sendpipeRelayUrl": "https://relay.sendpipe.org"
}

Custom SMTP:

json
{
  "provider": "smtp",
  "from": "no-reply@example.com",
  "host": "smtp.mailgun.org",
  "port": 587,
  "user": "...",
  "pass": "..."
}

Saving restarts GoTrue.

POST /dokwe-db/:id/auth/smtp#

Convenience alias that hard-codes provider: "smtp". Same body as the SMTP variant above minus provider.

POST /dokwe-db/:id/auth/email-hook#

⚠ Not for clients. This is the URL GoTrue's built-in email hook calls when SendPipe is configured. The class-level JwtAuthGuard is overridden on this route.

POST /dokwe-db/:id/auth/sms#

Twilio is the only supported provider today.

json
{
  "provider": "twilio",
  "accountSid": "AC…",
  "authToken": "32-char-twilio-token",
  "messageServiceSid": "MG…",
  "from": "+15551234567"
}

Saving restarts GoTrue with GOTRUE_EXTERNAL_PHONE_ENABLED=true and GOTRUE_SMS_AUTOCONFIRM=true (SMS verification is the confirmation step, so accounts auto-confirm on OTP).


14. Authentication — OAuth providers#

POST /dokwe-db/:id/auth/oauth/:provider#

provider is one of google, github, discord, gitlab, twitter.

json
{
  "enabled": true,
  "clientId": "...",
  "clientSecret": "..."
}

Pass enabled: false (with empty clientId/clientSecret) to remove the provider. Secrets are encrypted at rest.


15. Authentication — security settings#

POST /dokwe-db/:id/auth/security#

ts
{
  passwordMinLength?: number;        // 6 .. 128
  requireEmailConfirm?: boolean;     // ignored when no SMTP is configured
  accessTokenTtl?: number;           // seconds, 60 .. 86400
  allowedRedirectUrls?: string[];
}

Translates to GOTRUE_PASSWORD_MIN_LENGTH, GOTRUE_MAILER_AUTOCONFIRM, GOTRUE_JWT_EXP, GOTRUE_URI_ALLOW_LIST. Saving restarts GoTrue.


16. Authentication — user management#

These proxy to GoTrue's /admin/users API but require Dokwe platform auth, so dashboards don't have to ship the service role key.

GET /dokwe-db/:id/auth/users#

QueryDefault
page1
perPage50

Response shape matches GoTrue's user record.

POST /dokwe-db/:id/auth/users#

json
{
  "email": "user@example.com",
  "password": "min-6-chars",
  "emailConfirm": true,
  "userMetadata": { "name": "Ada" }
}

emailConfirm defaults to true so the manually-created account can sign in immediately.

GET /dokwe-db/:id/auth/users/:userId#

Single GoTrue user record.

DELETE /dokwe-db/:id/auth/users/:userId#

Permanently delete the user.

POST /dokwe-db/:id/auth/users/:userId/ban#

json
{ "ban": true }    // or false to unban

Implemented via GoTrue's ban_duration field — long-bans are 100 years.

POST /dokwe-db/:id/auth/users/:userId/reset-password#

json
{ "password": "new-password-min-6" }

Existing sessions stay valid until expiry — pair with a session revoke if you need an immediate sign-out.

PATCH /dokwe-db/:id/auth/users/:userId/metadata#

json
{
  "userMetadata": { "name": "Ada Lovelace" },
  "appMetadata": { "plan": "pro" }
}

Either field can be omitted; GoTrue merges the keys into existing metadata.


17. Authentication — sessions#

GET /dokwe-db/:id/auth/users/:userId/sessions#

Active sessions for the given user, read from auth.sessions:

ts
Array<{
  id: string;
  createdAt: string;       // ISO
  updatedAt: string;
  userAgent: string | null;
  ip: string | null;
  expiresAt: string | null;
}>

DELETE /dokwe-db/:id/auth/sessions/:sessionId#

Revoke (sign-out) a session. Removes the row from auth.sessions plus its refresh-token rows. Access tokens stay valid until expiry but can no longer be refreshed.


18. Authentication — audit logs#

GET /dokwe-db/:id/auth/logs#

Latest rows from auth.audit_log_entries. Auto-refreshing every 15s in the dashboard.

QueryDefault
page1
perPage50 (max 200)
ts
{
  logs: Array<{
    id: string;
    createdAt: string;
    ipAddress: string | null;
    action: 'login' | 'logout' | 'signup' | 'token_refreshed' | …;
    logType: string | null;
    actorId: string | null;
    actorUsername: string | null;
  }>;
  page: number;
  perPage: number;
}

19. Realtime#

GET /dokwe-db/:id/realtime/status#

json
{
  "status": "running",
  "port": 63000,
  "url": "wss://todo-app-rt.dokwe.com/socket",
  "failReason": null
}

POST /dokwe-db/:id/realtime/provision#

Idempotent — boots the supabase/realtime sidecar against this project's Postgres if it isn't already running. Used by the Realtime tab's "Provision" button to retro-fit projects that came up before milestone 1.

GET /dokwe-db/:id/realtime/publication#

Every public table + whether it's a member of supabase_realtime:

json
[ { "table": "todos", "subscribed": true }, { "table": "audit_log", "subscribed": false } ]

POST /dokwe-db/:id/realtime/publication/:table#

json
{ "subscribe": true }

Issues ALTER PUBLICATION supabase_realtime ADD TABLE "public"."<table>" (or DROP TABLE when subscribe: false). Subscribers stop / start receiving postgres_changes for that table without restarting the realtime container.


20. Storage#

Files live on the platform host's disk under /var/lib/dokwe/storage/<projectId>/<bucket>/<path>. Bucket names match /^[a-z0-9][a-z0-9-]{1,118}[a-z0-9]$/.

GET /dokwe-db/:id/storage/buckets#

ts
Array<{
  id: string;
  name: string;
  public: boolean;
  fileSizeLimit: number | null;
  createdAt: string;
}>

POST /dokwe-db/:id/storage/buckets#

json
{ "name": "avatars", "public": false, "fileSizeLimit": 10485760 }

DELETE /dokwe-db/:id/storage/buckets/:bucket#

Refuses if the bucket is non-empty.

GET /dokwe-db/:id/storage/buckets/:bucket/objects?prefix=#

ts
{
  bucket: { id: string; name: string; public: boolean };
  objects: Array<{
    id: string;
    path: string;
    size: number;
    mimeType: string | null;
    createdAt: string;
    updatedAt: string;
  }>;
}

Cap is 500 objects per call.

POST /dokwe-db/:id/storage/buckets/:bucket/upload?path=#

multipart/form-data with a single file part. ?path= overrides the filename. Re-uploads to the same path replace the file in place.

sh
curl -X POST \
  -H "Authorization: Bearer $JWT" \
  -F "file=@avatar.png" \
  "https://dokwe.com/api/dokwe-db/$ID/storage/buckets/avatars/upload?path=users/123.png"

Default size limit: 5 GB. Content-Type is recorded as the file's mimetype unless overridden by the bucket policy.

DELETE /dokwe-db/:id/storage/buckets/:bucket/object?path=#

GET /dokwe-db/:id/storage/buckets/:bucket/object?path=#

Auth-guarded download. Streams Content-Type + Content-Length from the recorded mimetype + size.

POST /dokwe-db/:id/storage/buckets/:bucket/sign#

Mint a short-lived signed URL.

json
{ "path": "users/123.png", "ttlSec": 3600 }
ts
{ token: string; expiresAt: string /* ISO */ }

The signed URL is:

code
<base>/dokwe-db/<id>/storage/signed/<bucket>/object?path=…&token=…

ttlSec defaults to 3600 (1 h); range is 30..604800 (30 s..7 d).

GET /dokwe-db/:id/storage/signed/:bucket/object?path=&token=#

⚠ No auth header required (the token is the credential). Refuses if the token doesn't match the project / bucket / path or has expired.

GET /dokwe-db/:id/storage/public/:bucket/object?path=#

⚠ No auth header required — and refuses if the bucket isn't marked public. Embeddable on websites; use this for <img src=...> etc.


21. AI assistant#

POST /dokwe-db/:id/ai/generate-schema#

json
{ "description": "A multi-tenant SaaS schema with users, organisations and projects." }
ts
{ sql: string; model: string }

The SQL is paste-ready (no markdown fences) and uses the conventions defined in the system prompt (UUID primary keys, created_at / updated_at, foreign-key cascades, role grants).

POST /dokwe-db/:id/ai/apply-schema#

json
{ "sql": "CREATE TABLE …;" }
json
{ "success": true }     // or { "success": false, "error": "..." }

POST /dokwe-db/:id/ai/generate-sql#

json
{ "question": "users who signed up in the last 7 days" }
ts
{ sql: string; model: string }

POST /dokwe-db/:id/ai/explain-sql#

json
{ "sql": "SELECT u.email, count(p.*) FROM users u LEFT JOIN posts p ..." }
ts
{ explanation: string; /* Markdown */ model: string }

22. Performance & security insights#

GET /dokwe-db/:id/security/scan#

Read-only audit of the public schema + RLS landscape.

ts
{
  score: number;            // 0–100, weighted by RLS coverage and findings count
  summary: { tables: number; tablesWithRls: number; policies: number };
  findings: Array<{
    severity: 'critical' | 'high' | 'medium' | 'low' | 'info';
    kind: 'rls_missing' | 'realtime_rls_missing' | 'policy_too_permissive' | 'sensitive_column';
    table?: string;
    column?: string;
    policy?: string;
    message: string;
    remediation?: string;
  }>;
}

GET /dokwe-db/:id/performance/metrics#

Top-25 slow queries from pg_stat_statements.

ts
{
  available: boolean;
  reason?: string;          // e.g. "pg_stat_statements is not loaded …"
  queries: Array<{
    query: string;
    calls: number;
    meanMs: number;
    totalMs: number;
    rows: number;
  }>;
}

If available is false, the user needs to add shared_preload_libraries = 'pg_stat_statements' to postgresql.conf and restart Postgres.

POST /dokwe-db/:id/performance/suggest-indexes#

AI-generated CREATE INDEX suggestions for the current slow-query mix. Body is empty.

ts
{
  available: boolean;
  reason?: string;
  suggestions: Array<{ statement: string; rationale: string }>;
  note?: string;
  model?: string;
}

Capped at 6 suggestions.


23. PostgREST runtime knobs & request log#

POST /dokwe-db/:id/api-config/pool-size#

json
{ "poolSize": 25 }

poolSize controls PGRST_DB_POOL — the maximum simultaneous DB connections PostgREST will hold open. When saturated, additional requests queue briefly (10s timeout). Range is 1–200; restart applies on save.

For local projects this also restarts the PostgREST container so the new ceiling takes effect immediately. For BYOS projects the value is saved and applied on the next deploy.

GET /dokwe-db/:id/request-logs#

Tail of the PostgREST container's stdout — one line per HTTP request.

QueryDefault
tail200 (range 10..1000)
json
{ "available": true, "logs": "10.0.0.4 - admin [...]\n..." }

For BYOS projects, returns { available: false, reason: "…" } for the moment — fetching logs through the agent is on the roadmap.


24. PostgREST / GoTrue / Realtime pass-through#

These services expose their canonical APIs at the URLs returned from GET /dokwe-db/:id (postgrestUrl, gotrueUrl, realtimeUrl). They're the unmodified Supabase containers, so the official SDKs and docs apply 1:1:

Use @supabase/supabase-js (or any Supabase-compatible client) with the project's postgrestUrl and anonKey. For storage, use this package's bundled DokweStorageClient — see @dokwe/js.