Skip to main content

API Documentation

Drafft includes an optional local REST API for reading and writing a loaded project. It is designed for integrations, tooling, and agents that need document-level access without clicking through the app.

tip

The API only works while Drafft is running and a project is loaded. The server listens on 127.0.0.1 only.

tip

If you are an LLM or an agent, start with Using the API as an Agent. It has the recommended workflows, payload discipline, and ownedBy / linkedBy semantics.

App Options​

  • Enable API: Starts the local REST API when a project is opened.
  • API Key: Required for read requests. Send it as x-api-key, or as Authorization: Bearer <key>.
  • API Port: The local port to listen on. Default 9001.
  • Enable Write API (preview): Enables write-capable endpoints.
  • Write API Key: Required for write requests. A read key cannot write.

Base URL:

http://127.0.0.1:9001

Discovery​

These endpoints do not require a key.

GET /
GET /v1/health
GET /v1/openapi.json

GET / returns the app version, API version, and whether the write API is enabled. GET /v1/openapi.json returns the full OpenAPI description.

The OpenAPI document includes request examples for Item, Actor, Quest, and Scenario creation, plus structured content schemas:

  • ItemContent — item text and canonical json
  • ActorContent — properties, bio, expressions, and canonical json
  • QuestContent — properties, conditions, json, and conditionsJson
  • ScenarioContent — legacy scenario/json plus collection-keyed collections
  • EditorLanguage — hjson, json, toml, yaml, or text
  • CreateAttachmentRequest and AttachmentMetadata — attachment uploads and metadata

Readiness​

GET /v1/ready

Returns the current readiness flags:

{
"ready": true,
"dbLoaded": true,
"variablesReady": true,
"searchReady": true,
"writesEnabled": false,
"writesReady": false
}

searchReady is false while the search index is being built. GET /v1/search returns 425 until it is ready.

Project info​

GET /v1/info

Returns the project name/version/description, app version, current user, capabilities, and readiness.

Documents​

Get one document​

GET /v1/documents/:id

Returns the raw database document, including _rev. Optional query parameters:

  • fields - comma-separated top-level fields to return, for example _id,name,type,collection,parent,path.
  • include - content or revs. Attachment stubs (content_type, length, digest) are always returned by GET /v1/documents/:id; attachments is accepted for compatibility. Use GET /v1/attachments/:id for the binary.
GET /v1/documents/abc123?fields=_id,name,type,collection,parent,path

Bulk fetch​

GET /v1/documents?ids=id1,id2,id3

Returns { items, missing }. Maximum 100 ids per request.

List collections​

GET /v1/collections
GET /v1/collections?includeInternal=true

Returns collection names with total and per-type counts:

{
"items": [
{ "collection": "Dialogue", "total": 12, "types": { "Dialogue": 10, "Folder": 2 } }
]
}

Internal collections such as User are excluded by default. Pass includeInternal=true to include them.

List documents in a collection​

GET /v1/collections/:name/documents?limit=50&offset=0&type=Dialogue&parent=<folderId>&q=aria
  • limit - 1 to 500, default 50.
  • offset - zero-based result offset, default 0.
  • type - filter by document type.
  • parent - filter by parent document id.
  • q - case-insensitive name/alias filter.
  • fields - field projection. Lists return a summary by default.
  • include=content (or fields=*) - return full documents, including content.

Returns { items, offset, limit, count, nextOffset, hasMore }. Use nextOffset for the next page while hasMore is true.

The default summary fields are _id, name, type, collection, parent, path, modified, locked, lockedBy, and alias. This keeps list responses small and usable in an LLM context; request include=content only when you need the document body.

Date fields in v1 read responses are normalized to ISO 8601. Bundles and exports keep the stored values.

Use the collection values returned by GET /v1/collections (for example Dialogue, Script, Actor). These are the database collection names, not the plural export-section names used by /game-export.

Folder children and ancestors​

GET /v1/documents/:id/children
GET /v1/documents/:id/ancestors

children returns direct children for a folder. ancestors returns the parent chain, root first.

Document state probe​

GET /v1/documents/:id/state

Reports the state a client needs before writing:

{
"id": "abc123",
"exists": true,
"collection": "Dialogue",
"type": "Dialogue",
"rev": "3-...",
"locked": false,
"lockedBy": null,
"lockOwnerType": null,
"tabOpen": true,
"tabKind": "main",
"wasModified": false,
"hasSemanticEdits": false,
"dirtyKind": null,
"selected": true,
"ready": true
}

wasModified is the raw buffer diff. hasSemanticEdits ignores runtime-only layout fields (measured, dragging, selected) and reflects authored changes. dirtyKind is "user", "normalization", or null.

If the document does not exist, the endpoint returns exists: false rather than an error.

Revisions​

GET /v1/documents/:id/revisions

Returns the revision id and the available revision list.

Dialogue nodes​

GET /v1/documents/:id/nodes
GET /v1/documents/:id/nodes?include=script

Lists the nodes of a dialogue:

{
"items": [
{
"id": "choice123",
"label": "How do you respond?",
"nodeType": "choice",
"scriptId": null,
"position": { "x": 20, "y": 270 },
"route": "/dialogue/dialogue123/node/choice123/script/undefined",
"handles": [
{
"id": "h1",
"type": "target",
"label": "In",
"portScript": null,
"isConditionOutput": false,
"conditionValue": null,
"isSwitchOutput": false,
"caseValue": null,
"isDefault": false
},
{
"id": "h2",
"type": "source",
"label": "Show compassion",
"portScript": "@set variables.player.path = \"empathy\"",
"isConditionOutput": false,
"conditionValue": null,
"isSwitchOutput": false,
"caseValue": null,
"isDefault": false
}
],
"script": null
}
],
"edges": [
{
"id": "e1",
"source": "choice123",
"sourceHandle": "h2",
"target": "response123",
"targetHandle": "h3",
"label": null
}
]
}

handles are the node’s ports. A portScript runs when that port is followed; the node’s script runs when the node is reached. edges links source/sourceHandle to target/targetHandle, so you can follow a choice to its response node.

With include=script, each node includes its script document, so you can read a dialogue and its lines in one call. Without it, the response only contains scriptId.

Returns 400 not_a_dialogue for non-dialogue documents. Use the route to open the dialogue focused on that node.

References​

GET /v1/documents/:id/references?direction=incoming|outgoing|both

Returns structural links to and from a document. This is computed on demand from the current project data; there is no secondary index to get out of sync.

{
"incoming": [
{
"direction": "incoming",
"kind": "dialogue-node-script",
"confidence": "structural",
"docId": "dialogue123",
"docName": "3 - Memory Exploration",
"nodeId": "node123",
"nodeLabel": "Destiny unfolds",
"route": "/dialogue/dialogue123/node/node123/script/script123"
}
],
"outgoing": [
{
"direction": "outgoing",
"kind": "dialogue-script-folder",
"confidence": "structural",
"docId": "folder123",
"docName": "3 - Memory Exploration",
"route": "/folder/folder123"
}
]
}

Currently covered:

  • dialogue → script folder, node scripts, related docs
  • script → parent folder, owning dialogue
  • scene → playlist items
  • GDD → :doc{#id} links
  • incoming: dialogue node → script, scene → dialogue/script, GDD → document, related docs

Textual mentions (variable/actor names inside scripts) are not included yet.

Attachments​

Attachments are Attachment documents with one stored blob. The API creates, reads, and deletes them. Bundle import never carries _attachments; use these endpoints instead.

Create an attachment​

POST /v1/attachments
x-api-key: <write-key>
content-type: application/json

{
"name": "cover.png",
"mimeType": "image/png",
"data": "<base64>",
"id": "optional-url-safe-id"
}

data must be standard base64 (A–Z, a–z, 0–9, +, /). Padding (=) is required when the input byte length is not divisible by three. Whitespace and a data:<mime>;base64,... prefix are ignored; URL-safe (-, _) input is rejected. mimeType is inferred from name when omitted. id is optional and follows the same ^[A-Za-z0-9_-]{1,128}$ rule as documents. The decoded file is limited to 25 MiB.

The response is 201 with metadata; the binary is never echoed:

{
"_id": "abc123",
"_rev": "1-...",
"name": "cover.png",
"mimeType": "image/png",
"size": 18234,
"digest": "md5-...",
"permalink": "drafft://image/abc123"
}

Multipart uploads use the same route:

curl -X POST "http://127.0.0.1:9001/v1/attachments" \
-H "x-api-key: $WRITE_KEY" \
-F "file=@cover.png" \
-F "name=cover.png"

The file part can be named anything; the first file part is used. name and mimeType form fields override the part filename and type. Existing ids return 409 id_exists. Deleted ids cannot be reused because PouchDB keeps a tombstone.

Read an attachment​

GET /v1/attachments/:id
GET /v1/attachments/:id?meta=1
HEAD /v1/attachments/:id

The default response is the raw file with Content-Type, Content-Length, Content-Disposition: attachment, ETag, and X-Content-Type-Options: nosniff. Use ?meta=1 for the JSON metadata shown above. HEAD returns the same headers without reading the blob.

ETag is the PouchDB revision. Send it back as If-None-Match to get 304 Not Modified.

The API always returns the latest revision and does not support HTTP Range requests. Large media should use the in-app drafft:// permalink or download the whole file.

Delete an attachment​

DELETE /v1/attachments/:id?rev=<current-rev>
x-api-key: <write-key>

The current _rev is required (428 rev_required when missing, 409 stale_rev when it changed). If-Match: "<rev>" is accepted instead of the query parameter. Only Attachment documents can be deleted through this route.

{ "deleted": true, "id": "abc123", "rev": "2-..." }

Deletion writes a PouchDB tombstone. PouchDB's local attachment store deduplicates identical blobs by digest and keeps a blob while any stored revision references it, so deleting one attachment does not remove shared bytes. The old revision and its bytes remain until the database is compacted. If the project syncs to CouchDB, the tombstone replicates and the remote server applies its own limits and compaction policy.

List attachments​

Use the existing collection listing:

GET /v1/collections/Attachment/documents?limit=50
GET /v1/collections/Attachment/documents?limit=50&include=content

The default summary omits _attachments; use GET /v1/attachments/:id?meta=1 for size and digest.

Bundles​

A bundle is a partial project export in the same { rows } shape used by project backups. It can be imported into another project.

GET /v1/documents/:id/bundle
GET /v1/documents/:id/bundle?dependencies=true

With dependencies=true, a Dialogue bundle also includes its script folder and node scripts.

GET /v1/documents/export?ids=id1,id2
GET /v1/documents/export?collection=Dialogue

Use either ids or collection, not both. Bundles keep the current _rev so a later update can use it as a precondition. Locks, revision history (_revisions, _revs_info), attachments, and runtime dialogue layout fields (measured, dragging, selected) are omitted.

Add stripRev=true to omit _rev, for example when exporting a template:

GET /v1/documents/:id/bundle?stripRev=true
GET /v1/documents/export?collection=Dialogue&stripRev=true

Write API​

Write endpoints require the write API key and a project whose writesReady flag is true. A read key cannot write. This preview supports creating documents, importing bundles in create/update/upsert mode, content-only updates for Script, Gdd, Item, Actor, and Quest documents, and creating/reading/deleting attachments. Document delete is not available yet.

Create one document​

POST /v1/documents

Body:

{
"name": "New dialogue",
"type": "Dialogue",
"collection": "Dialogue",
"parentId": null,
"id": "optional-url-safe-id",
"content": { "tree": { "nodes": [], "edges": [] } },
"props": null
}
  • name and type are required.
  • collection defaults to type; it is required for Folder and is the folder's section (for example Script).
  • parentId must reference a Folder in the same collection.
  • id is optional and must match ^[A-Za-z0-9_-]{1,128}$.
  • content is merged into the type's default content. props is used by types such as Kanban.
  • editorLanguage is optional for Item, Actor, and Quest. New structured documents default to hjson.
  • The response is 201 with the created document, including _rev and the recomputed path.

Creating an existing id returns 409 id_exists. Internal types (ProjectSettings, User, Attachment, …) cannot be created through this endpoint.

Variable documents are variable sets. The root variable name is content.json._sid; the document name and id are labels. For example:

{
"name": "Player",
"type": "Variable",
"content": {
"variables": "_sid: player\nstyle: A",
"json": "{\"_sid\":\"player\",\"style\":\"A\"}"
}
}

Scripts address it as variables.player.style. content.variables and content.json should agree.

Structured documents and _sid​

Item, Actor, and Quest documents keep editable text plus a canonical JSON payload:

  • Item: content.item → content.json
  • Actor: content.properties → content.json
  • Quest: content.properties → content.json, content.conditions → content.conditionsJson

Add a top-level _sid to the payload to make the document addressable from scripts (${q.questA.title}, ${i.sword.damage}, ${a.kenji.age}). A missing _sid is allowed and makes the document legacy/unaddressable; it is not a validation error.

When both text and canonical JSON are supplied, they must agree. The API never regenerates editable text from JSON.

Document formats are client-side​

The API stores the editable text as-is and never rewrites it from JSON. For Item, Actor, and Quest documents, editorLanguage tells Drafft how to interpret the text. Supported values include hjson, json, toml, yaml, and text. (Legacy Misc documents still store editor text, but are outside the structured state model.)

If editorLanguage is omitted and the content already has a canonical JSON payload, Drafft treats the text as hjson so the canonical payload is not discarded; the inferred language is stored on the next write. Documents without a canonical payload keep the plain-text behavior.

Writes parse the text to validate it and rebuild the canonical JSON payload (content.json, or content.conditionsJson for Quest conditions); invalid text is rejected. Changing editorLanguage from, for example, toml to hjson does not convert the text — the existing text is reinterpreted under the new language and the write fails if it does not parse. If you convert a document:

  1. Parse the current format yourself.
  2. Rewrite the content in the target format.
  3. Update both content and editorLanguage in the same write.

There is no server-side schema inference, especially for text documents. A plain-text document stays plain text until the client supplies a structured representation.

Import a bundle​

POST /v1/documents/import
POST /v1/documents/import?dryRun=true
POST /v1/documents/import?mode=update
POST /v1/documents/import?mode=upsert

The body is a bundle:

{
"rows": [
{ "id": "folder1", "doc": { "_id": "folder1", "name": "Folder", "type": "Folder", "collection": "Script", "parent": null } },
{ "id": "script1", "doc": { "_id": "script1", "name": "Child", "type": "Script", "collection": "Script", "parent": "folder1", "_rev": "1-..." } }
]
}

Modes:

  • create (default) adds new documents. Existing ids are conflicts.
  • update requires every document to exist and, by default, to include the current _rev.
  • upsert creates missing documents and updates existing ones.
  • revPolicy=current allows an existing document without _rev to use its current revision. A supplied but stale _rev is still a conflict.

Import:

  • strips incoming locks, revision history, attachments, and tree fields;
  • treats parent as authoritative and recomputes path and children;
  • updates parent/name/tree changes for update/upsert, including descendant paths and Dialogue script-folder names;
  • validates ids, types, collections, parents, Dialogue script folders, and dependency cycles;
  • orders parents and dialogue dependencies before their children;
  • requires a free document for each update: no unsaved semantic tab edits and no lock;
  • is not transactional. Created documents are rolled back (best effort) if a write fails; updates already applied remain.

dryRun=true returns the plan without writing. Conflicts return 200 with valid: false in dry-run, or 409 import_conflict for a real import. Validation errors return 400 validation_failed with per-row errors in error.details.

Response shape:

{
"mode": "upsert",
"dryRun": false,
"valid": true,
"summary": { "total": 5, "create": 1, "created": 1, "update": 4, "updated": 4, "conflict": 0, "invalid": 0, "failed": 0 },
"actions": [
{ "id": "script1", "action": "updated", "rev": "2-...", "path": "Folder.Child" },
{ "id": "script2", "action": "created", "rev": "1-...", "path": "Folder.New Child" }
]
}

Clients may also wrap the bundle as { "bundle": { "rows": [...] } } and put mode, revPolicy, or dryRun in the body.

Update one document's content​

PATCH /v1/documents/:id
PATCH /v1/documents/:id?dryRun=true

Body:

{
"rev": "2-...",
"content": { "script": "...full updated script..." }
}

This endpoint is content-only. It supports Script (content.script), Gdd (content.gdd), Item (content.item), Actor (content.properties), and Quest (content.properties plus content.conditions). It replaces the whole content object. It does not rename, reparent, delete, or change locks.

Rules:

  • rev is required; missing → 428 rev_required.
  • stale rev → 409 stale_rev with currentRev.
  • an open tab with semantic unsaved edits → 409 dirty_buffer.
  • a locked document → 423 locked.
  • a clean, unlocked open tab is allowed and refreshed.
  • dryRun=true validates without writing, including structured-content parsing and _sid uniqueness.
  • editorLanguage may be supplied for structured documents and is applied atomically with content.

Success returns the updated document and a nudge:

{
"document": { "_id": "script1", "_rev": "3-...", "content": { "script": "..." } },
"nudge": "Updated goToLibrary. New rev is 3-...; re-read before the next edit."
}

Runtime state​

  • Variable updates go through the same state-store path as the Variable editor. Successful API updates refresh live variable defaults and migrate live values when _sid changes.
  • Scenario updates change the stored scenario document only. They do not activate it or replace live state. Applying a scenario remains an explicit action, as it is in the UI.
  • The API does not expose live-scenario activation, reset, or direct live-variable writes.
GET /v1/search?q=aria&scope=documents&collection=Actor&type=Actor&limit=20&offset=0
GET /v1/search?q=garden&scope=nodes
GET /v1/search?q=garden&scope=all

scope is documents (default), nodes, or all. Document results have kind: "document"; dialogue node results have kind: "node" and their own score and snippet. Node results use collection: "Dialogue" and type: "DialogueNode", so type=Dialogue filters documents only and type=DialogueNode filters nodes.

Document result:

{
"kind": "document",
"id": "abc123",
"name": "Aria",
"collection": "Actor",
"type": "Actor",
"path": "Characters.Aria",
"score": 12.4,
"snippet": "..."
}

Dialogue document results also include matching nodes and a focus target:

{
"kind": "document",
"id": "dialogue123",
"name": "1 - Opening Scene",
"collection": "Dialogue",
"type": "Dialogue",
"nodeMatches": [
{ "id": "node123", "label": "Enter the garden", "scriptId": "script123" }
],
"focus": {
"nodeId": "node123",
"label": "Enter the garden",
"scriptId": "script123",
"route": "/dialogue/dialogue123/node/node123/script/script123"
}
}

Node result (scope=nodes or scope=all):

{
"kind": "node",
"id": "node123",
"dialogueId": "dialogue123",
"dialogueName": "1 - Opening Scene",
"nodeId": "node123",
"label": "Enter the garden",
"nodeType": "script",
"scriptId": "script123",
"route": "/dialogue/dialogue123/node/node123/script/script123",
"score": 9.8,
"snippet": "...",
"collection": "Dialogue",
"type": "DialogueNode"
}

The query must be at least 2 characters. limit is capped at 100. Node search ignores common stopwords (the, a, of, etc.) so a query does not focus an unrelated node.

Errors​

All v1 endpoints return errors in the same shape:

{
"error": {
"code": "not_found",
"message": "Document not found: abc123",
"reason": null,
"details": null
}
}

Common status codes:

StatusMeaning
400Malformed request or missing parameter
401Missing or invalid read key
403Write API disabled or write key required
404Document or route not found
409Conflict, such as an existing id, stale revision, or dirty tab
413Attachment or request body exceeds the size limit
423Document is locked
425Project or search index not ready
428A required rev is missing
500Unexpected server error

Legacy endpoints​

These endpoints remain available for existing integrations.

Get project info and settings​

GET /info

Get game export​

Gets a game-ready JSON object. Same as clicking "Export Game Content" in the app.

GET /game-export

The exported collections come from the project settings, and can be filtered with a comma-separated collections parameter:

  • ProjectSettings, GDD, Scripts, Dialogues, Actors, Quests, Items, Variables, Scenarios, Scenes, Misc, Grids, Kanban, Canvas, Maps
GET /game-export?collections=Scripts,Dialogues,Variables,Scenarios

Get JSON Schema export​

GET /schema-export
GET /schema-export?collections=Scripts,Dialogues

Get database dump​

Gets a raw PouchDB dump. This is a backup endpoint, not a normal read endpoint. It accepts PouchDB allDocs options; defaults are include_docs: true and attachments: true.

GET /db-dump
GET /db-dump?include_docs=false&attachments=false

Opens a document in the app.

GET /navigate?id=DOCUMENT_ID

To focus a specific dialogue node, add nodeId (and optionally scriptId):

GET /navigate?id=DIALOGUE_ID&nodeId=NODE_ID
GET /navigate?id=DIALOGUE_ID&nodeId=NODE_ID&scriptId=SCRIPT_ID

The response includes the resolved route. The app opens the dialogue, centers the node, and opens its script subtab when a script is available.