> ## Documentation Index
> Fetch the complete documentation index at: https://docs.omni.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Create draft and patch document

> Create a new draft on the published document and apply the patch in one call. There is no auto-publish — the response includes the new `draftIdentifier` for follow-up calls. Pass an optional `branchId` to attach the draft to a branch; omit it for a draft on the main (unpublished) workspace.


## Draft → publish workflow

Editing an existing document is a three-step flow:

1. **`PATCH /api/v2/documents/{documentId}/draft`** *(this endpoint)* — creates a new draft on the published document and applies your patch. Returns the new `draftIdentifier`.
2. *(optional)* [**`PATCH /api/v2/documents/{documentId}/draft/{draftId}`**](/api/documents-v2/patch-draft) — apply further patches to that draft.
3. [**`POST /api/v2/documents/{documentId}/draft/publish`**](/api/documents-v2/publish-draft) — publish the main draft live.

A document may have only one main draft at a time. If one already exists, this endpoint returns `409` — patch the existing draft (step 2) or publish/discard it first. This replaces v1's `clearExistingDraft` flag, which **does not exist** in v2.

A `GET` response is a valid `PATCH` body — [read the current state](/api/documents-v2/get-document-state), edit it, and submit it back verbatim.

## Field constraints

| Field                                       | Limit                           | Error (`400`)                                                         |
| ------------------------------------------- | ------------------------------- | --------------------------------------------------------------------- |
| `name` (document)                           | 1–254 characters                | `name cannot be empty` · `name must be 254 characters or fewer`       |
| `summary`                                   | 1–255 characters, optional      | `summary cannot be empty` · `summary must be 255 characters or fewer` |
| `queryPresentations.data.{key}.name`        | 1–144 characters                | `name must be 144 characters or fewer`                                |
| `queryPresentations.data.{key}.subTitle`    | ≤ 250 characters                | `subTitle must be 250 characters or fewer`                            |
| `queryPresentations.data.{key}.description` | ≤ 500 characters                | `description must be 500 characters or fewer`                         |
| `queryPresentations.data`                   | ≤ 48 non-null entries per patch | `A single patch may carry at most 48 query presentations.`            |

`summary` is an audit-trail note describing the change (never returned by reads); when omitted the server generates one from the touched sections. Null `queryPresentations.data` entries (deletions) do not count toward the 48-entry cap.

## Addressing tiles (no `miniUuid`)

Tiles are addressed by their record key in `queryPresentations.data` (e.g. `"2"`). The server owns internal tile identity, so you never send or manage `miniUuid`:

* **New key** → a new tile is created.
* **Existing key, identical content** (a verbatim round-trip of a `GET`) → treated as a **no-op** and dropped from the patch.
* **Existing key, changed content** → the tile is updated (the server regenerates its internal identifier).
* **`linked`-type tabs** always re-resolve — they are excluded from no-op detection.
* Query presentations are immutable server-side: replace a tile by key, don't mutate it in place.

`data` is **shallow-merged** by key — omitted keys are untouched; `data.{key}: null` deletes that tile. `order`, when present, replaces the tab order. `controls` and `settings` are likewise shallow-merged; `containers`, when present, fully replaces the layout.

## AI summaries via linked tiles

There is no `narrative` field. To attach an AI-style summary that reuses another tile's query, add a `linked`-type query presentation whose `sourceQueryPresentationKey` points at the source tile's record key (a string such as `"2"` — **not** a positional index into `order`):

```json
{
  "queryPresentations": {
    "data": {
      "3": {
        "type": "linked",
        "name": "Summary",
        "sourceQueryPresentationKey": "2"
      }
    }
  }
}
```


## OpenAPI

````yaml /api/openapi.yaml patch /v2/documents/{documentId}/draft
openapi: 3.1.0
info:
  title: Omni API
  description: >
    The Omni REST API provides programmatic access to your Omni instance for
    managing users, documents, queries, schedules, and more.  
  version: 1.0.0
  contact:
    name: Omni Support
    url: https://docs.omni.co
servers:
  - url: https://{instance}.omniapp.co/api
    description: Production
    variables:
      instance:
        default: blobsrus
        description: Your production Omni instance subdomain
  - url: https://{instance}.playground.exploreomni.dev/api
    description: Playground
    variables:
      instance:
        default: blobsrus
        description: Your playground Omni instance subdomain
security:
  - bearerAuth: []
  - orgApiKey: []
tags:
  - name: Who Am I
    description: Inspect your own user permissions
  - name: AI
    description: AI-powered query generation
  - name: AI Credit Controls
    description: Manage organization-level AI credit usage
  - name: AI Eval
    description: >-
      AI evaluation: manage prompt sets and runs used to score AI quality
      against curated prompt suites.
  - name: AI Model Suggestions
    description: Manage AI-generated suggestions for shared models
  - name: AI Routines
    description: >-
      Manage AI Routines: schedule recurring AI-powered tasks to run
      automatically on your data.
  - name: Documents v2
    description: >
      A draft-based workflow for creating and editing documents: create a
      document, patch a draft, then publish. Replaces the one-shot `PUT`/`PATCH`
      v1 document write endpoints.
  - name: Documents
    description: Create, retrieve, and manage documents
  - name: API Tokens
    description: >-
      Manage API tokens (Organization keys, Personal Access Tokens, MCP OAuth
      grants)
  - name: Connections
    description: Manage database connections
  - name: Connection environments
    description: Manage connection environments database connections
  - name: Content
    description: Unified content retrieval (documents and folders)
  - name: Content migration
    description: Export and import dashboards
  - name: Content validator
    description: Validate content against models and perform find/replace operations
  - name: Dashboard downloads
    description: Download dashboards and tiles as PDF, PNG, XLSX, CSV, or JSON files
  - name: Dashboard filters and controls
    description: Read and update dashboard filter and control default values
  - name: dbt
    description: Manage dbt configuration for connections
  - name: Document favorites
    description: Favorite and unfavorite documents
  - name: Document labels
    description: Apply and manage labels on documents
  - name: Document permissions
    description: Manage document-level access
  - name: Labels
    description: >
      Manage labels in an organization. Labels can be applied to documents and
      folders to help organize and categorize content.


      **Label types:**

      - **Basic labels**: Can be created and managed by any user

      - **Verified labels**: Indicate curated or officially sanctioned content.
      Admin-only.

      - **Homepage labels**: Appear on the organization homepage. Admin-only.
  - name: Folders
    description: Create and organize content folders
  - name: Folder permissions
    description: Manage folder-level access
  - name: Jobs
    description: Check status of asynchronous jobs
  - name: Models
    description: Create and manage data models
  - name: Model branches
    description: Manage model branches and merge changes
  - name: Model git configuration
    description: Manage git configuration for shared models
  - name: Queries
    description: Execute workbook queries
  - name: Schedules
    description: Create and manage scheduled tasks
  - name: Schedule recipients
    description: Manage schedule recipients
  - name: Schema refresh schedules
    description: Manage automated schema refresh schedules for connections
  - name: Topics
    description: Retrieve topic information from models
  - name: Uploads
    description: Manage file uploads
  - name: Users
    description: Manage users
  - name: User attributes
    description: Manage user attribute definitions
  - name: User groups
    description: Manage user groups
  - name: User model roles
    description: Manage model and connection role assignments for users
  - name: User group model roles
    description: Manage model and connection role assignments for user groups
  - name: Uploads
    description: Manage CSV and spreadsheet uploads
paths:
  /v2/documents/{documentId}/draft:
    patch:
      tags:
        - Documents v2
      summary: Create draft and patch document
      description: >
        Create a new draft on the published document and apply the patch in one
        call. There is no auto-publish — the response includes the new
        `draftIdentifier` for follow-up calls. Pass an optional `branchId` to
        attach the draft to a branch; omit it for a draft on the main
        (unpublished) workspace.
      operationId: documentsV2PatchDraft
      parameters:
        - name: documentId
          in: path
          required: true
          schema:
            type: string
          description: >-
            The published document's URL slug (e.g. `abc123`) or its canonical
            workbook UUID.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DocumentsV2CreateDraftBody'
            examples:
              metadataOnly:
                summary: Rename the document and tweak a setting
                value:
                  name: Q2 Revenue (final)
                  summary: Rename and enable cross-filtering
                  settings:
                    crossfilterEnabled: true
              contentOnly:
                summary: Add a tile and delete another
                value:
                  queryPresentations:
                    data:
                      '3':
                        type: query
                        name: Orders by region
                        topicName: order_items
                        query:
                          fields:
                            - users.state
                            - order_items.count
                      '4': null
              linkedSummary:
                summary: Attach an AI summary linked to tile "2"
                value:
                  queryPresentations:
                    data:
                      '5':
                        type: linked
                        name: Summary
                        sourceQueryPresentationKey: '2'
              onBranch:
                summary: Create the draft on a branch
                value:
                  branchId: 8b1f0a2c-1234-4abc-9def-0123456789ab
                  name: Q2 Revenue (branch edit)
      responses:
        '200':
          description: Draft created and patch applied successfully.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DocumentsV2PatchDraftResponse'
              example:
                identifier: q2-revenue
                draftIdentifier: q2-revenue-draft-7f3a
                name: Q2 Revenue (final)
                description: Quarterly revenue review
        '400':
          description: >
            Invalid request body or schema validation error — for example an
            unknown top-level field, a length cap exceeded, or the
            query-presentation cap exceeded (`A single patch may carry at most
            48 query presentations.`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Authentication required.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '403':
          description: Insufficient permissions to update the document.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Document or branch not found.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '405':
          $ref: '#/components/responses/MethodNotAllowed'
        '409':
          description: >
            The target is not a published document (drafts only attach to
            published documents) — for example a draft already exists for this
            document — or a concurrent request just created its layout; retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '422':
          description: >
            The document cannot satisfy the patch: a classic-layout dashboard
            (upgrade to the advanced layout first), an app document, or a
            workbook-only document patched without a `containers` payload (or
            with an empty one).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - bearerAuth: []
components:
  schemas:
    DocumentsV2CreateDraftBody:
      type: object
      additionalProperties: false
      description: >-
        The draft-route patch body plus an optional `branchId` selecting the
        branch the new draft is attached to.
      properties:
        branchId:
          type: string
          format: uuid
          description: >-
            Branch the draft is created on. Omit for a draft on the main
            (unpublished) workspace.
        name:
          type: string
          minLength: 1
          maxLength: 254
          description: Document name.
        description:
          type:
            - string
            - 'null'
          description: Document description.
        summary:
          type: string
          minLength: 1
          maxLength: 255
          description: >-
            Caller-supplied description of what this patch changes, written to
            the history audit trail. When omitted, Omni auto-generates one from
            the updated sections.
        queryPresentations:
          $ref: '#/components/schemas/DocumentsV2QueryPresentationsPatch'
        controls:
          $ref: '#/components/schemas/DocumentsV2ControlsPatch'
        settings:
          $ref: '#/components/schemas/DocumentsV2SettingsPatch'
        containers:
          allOf:
            - $ref: '#/components/schemas/DocumentsV2Containers'
            - description: >-
                Container layout. When present, fully replaces the existing
                layout.
    DocumentsV2PatchDraftResponse:
      type: object
      required:
        - description
        - draftIdentifier
        - identifier
        - name
      properties:
        identifier:
          type: string
          description: Published document identifier the draft targets.
        draftIdentifier:
          type: string
          description: Identifier of the draft the patch was applied to.
        name:
          type: string
          description: Document name.
        description:
          type:
            - string
            - 'null'
          description: Document description.
    Error:
      type: object
      properties:
        error:
          type: string
          description: HTTP response code for the error
          example: <response_code>
        message:
          type: string
          description: Detailed error description
          example: <error_reason>
    DocumentsV2QueryPresentationsPatch:
      type: object
      description: Query presentations (tabs/tiles) keyed by record key.
      properties:
        data:
          type: object
          description: >
            Tabs keyed by record key (a positive-integer string, e.g. `"1"`,
            `"2"`). Shallow-merged by key — omitted keys are untouched; set a
            key to `null` to delete that tab. Capped at 48 non-null entries per
            patch.
          additionalProperties:
            oneOf:
              - $ref: '#/components/schemas/DocumentsV2QueryPresentation'
              - type: 'null'
        order:
          type: array
          description: Tab display order. When present, replaces the existing order.
          items:
            type: string
            pattern: ^[1-9][0-9]*$
    DocumentsV2ControlsPatch:
      type: object
      description: Dashboard filters/controls keyed by control ID.
      properties:
        data:
          type: object
          description: >-
            Controls keyed by control ID. Shallow-merged by key — omitted keys
            are untouched; set to `null` to delete.
          additionalProperties:
            oneOf:
              - $ref: '#/components/schemas/DocumentsV2Control'
              - type: 'null'
        order:
          type: array
          description: >-
            Display order for controls. When present, replaces the existing
            order.
          items:
            type: string
    DocumentsV2SettingsPatch:
      type: object
      description: Document settings. Shallow-merged with the existing settings.
      properties:
        crossfilterEnabled:
          type: boolean
          description: >-
            When true, clicking a value in one tile filters all other tiles on
            the dashboard.
        customText:
          type:
            - object
            - 'null'
          description: Custom text replacing default UI strings on the dashboard.
          properties:
            queryError:
              type: string
              description: >-
                Custom text shown when a query errors, replacing the default
                error text.
            queryNoResults:
              type: string
              description: >-
                Custom text shown when a query returns no results, replacing the
                default empty state.
        facetFilters:
          type: boolean
          description: >-
            When true, dashboard filters are applied per-facet when faceting is
            active.
        refreshInterval:
          type:
            - number
            - 'null'
          description: Auto-refresh interval in seconds. Null disables auto-refresh.
        runQueriesOn:
          type:
            - string
            - 'null'
          enum:
            - current-page
            - all-pages
            - null
          description: >-
            Controls whether dashboard queries execute on the visible page or
            across all pages.
    DocumentsV2Containers:
      type: array
      description: >
        Container layout array (grid / stack / page / reference containers,
        recursively nested). On a patch, when present this **fully replaces**
        the existing layout. The server validates the full structure on apply;
        container `instanceKey` / `referenceKey` values round-trip unchanged.
        See the dashboard layout reference for the complete grammar.
      items:
        type: object
        additionalProperties: true
    DocumentsV2QueryPresentation:
      type: object
      required:
        - type
      description: >
        A single tab/tile. The server owns internal tile identity — callers
        never send `miniUuid`; tiles are addressed by their record key in
        `queryPresentations.data`.
      properties:
        type:
          type: string
          enum:
            - blank
            - csv
            - query
            - dataset
            - spreadsheet
            - sql
            - dbt
            - query-view
            - linked
            - app
          description: >-
            The query presentation type. `query` is a semantic query; `sql` is
            raw SQL; `linked` reuses another tile's query (see
            `sourceQueryPresentationKey`).
        name:
          type: string
          minLength: 1
          maxLength: 144
          description: User-provided tab name.
        subTitle:
          type:
            - string
            - 'null'
          maxLength: 250
          description: User-provided tab subtitle.
        description:
          type:
            - string
            - 'null'
          maxLength: 500
          description: User-provided tab description.
        sourceQueryPresentationKey:
          type:
            - string
            - 'null'
          pattern: ^[1-9][0-9]*$
          description: >
            For `linked`-type tabs, the record key — the same identifier used as
            a `queryPresentations.data` key — of the source tile whose query
            this tab reuses. Null for all other tab types. This is a tile record
            key, **not** a positional index into `order`.
        topicName:
          type:
            - string
            - 'null'
          description: The topic (explore) this query is built on.
        isSql:
          type:
            - boolean
            - 'null'
          description: Whether this tab is in raw SQL mode.
        prefersChart:
          type: boolean
          description: >-
            When true, the chart view is shown by default instead of the data
            table.
        automaticVis:
          type:
            - boolean
            - 'null'
          description: >-
            When true, the system automatically selects the best visualization
            type.
        filterOrder:
          type: array
          items:
            type: string
          description: >-
            Ordered list of filter field names controlling display order on this
            tab.
        editingModelObjectName:
          type:
            - string
            - 'null'
          description: >-
            Model object (view/topic) currently being edited via the
            dataset/query-view editor. Applies only to `dataset` / `query-view`
            tabs — omitted from reads and rejected on patches for other tab
            types.
        editingModelObjectNameChange:
          type:
            - string
            - 'null'
          description: >-
            Pending rename of the model object being edited. Applies only to
            `dataset` / `query-view` tabs — omitted from reads and rejected on
            patches for other tab types.
        query:
          type:
            - object
            - 'null'
          additionalProperties: true
          description: >-
            The semantic query for this tab (fields, filters, sorts, limits,
            etc.), minus the server-owned workbook model anchors. Omitted on a
            no-op replay; the server anchors new/changed tiles to the draft.
        visConfig:
          type:
            - object
            - 'null'
          additionalProperties: true
          description: Visualization configuration for the tile.
        resultConfig:
          type: object
          additionalProperties: true
          description: >-
            Result display configuration (column widths, frozen columns,
            conditional formatting, number formatting, etc.).
        aiConfig:
          type:
            - object
            - 'null'
          additionalProperties: true
          description: >-
            AI-generated metadata config (subtitle/description auto-generation
            settings).
    DocumentsV2Control:
      type: object
      additionalProperties: true
      description: >
        A dashboard control (filter). The full config grammar — control type,
        field bindings, filter values, and (for multi-field filters) the
        recursive composite-filter grammar — is validated by the server on
        apply. See the dashboard filters & controls reference for the complete
        structure.
  responses:
    MethodNotAllowed:
      description: Method Not Allowed - Invalid HTTP method for this endpoint
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        Can be either an [Organization API
        Key](/api/authentication#organization-api-keys) or [Personal Access
        Token (PAT)](/api/authentication#token-types).


        Include in the `Authorization` header as: `Bearer YOUR_TOKEN`
    orgApiKey:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >
        Requires an [Organization API
        Key](/api/authentication#organization-api-keys). Personal Access Tokens
        (PATs) are not supported for this endpoint.


        Include in the `Authorization` header as: `Bearer ORGANIZATION_API_KEY`

````