# POST /api/v2/drive-documents/{drive_document}/actions/edit

Edit blocks of a document

- MCP id: drive-documents.actions.edit
- Scope: api:write:project_drive
- Scope: api:write:customer_drive
- Scope: api:write:organization_drive
- Scope: api:write:user_drive
- Permission: project_drive::create
- Rate cost: 1 unit, write bucket. A write costs the same whatever `view` you ask for.
- Cache-Control: private, no-store

Changes a document block by block, the way a collaborator in the editor does, instead of rewriting the whole body.

Read the blocks and their ids with `GET /api/v2/drive-documents/{drive_document}?include=blocks`, then send `operations`, applied in order, each on the result of the ones before. `insert_before` and `insert_after` add the blocks in `markdown` next to `block_id`; `replace` puts them in its place, and the first of them keeps its id (one block of the same kind updates it where it is, so what someone types in it meanwhile stays); `delete` removes the block; `set_checked` ticks a task (`taskItem`) on or off; `replace_text` swaps the one occurrence of `find` in the block for `replace` (empty or left out removes it) and keeps its formatting. `markdown` is extended Markdown, the notation of `content_extended`. Next to a list item, or in its place, it must be a list of items of the same kind (`- [ ] …` for a task). Blocks you do not name are not touched at all, so their formatting cannot be lost and whatever others type meanwhile is merged rather than overwritten; anyone with the document open sees the change at once, made by your token. The operations apply together or not at all: a refused one answers `422` naming it, such as an unknown `block_id` or a `find` that occurs more or less than once, and nothing changes. Send `If-Match` with the `ETag` of your read to have the edit refused with `412` when the document changed since. `replace` and `delete` must send the block's `version` from that read, and any operation may: when the block changed since, for example because someone is typing in it, the edit answers `409` `state-conflict` with `conflict.block_id` and nothing is written, so read the blocks again. Changes elsewhere in the document do not count. Add `?include=blocks` to get the blocks back with the ids of new ones. The collaboration server applies the edit, so while it is unavailable the edit answers `422`. The declared permission is `project_drive::create` (editing is part of the create permission); the other three drive prefixes apply by the owning item's owner type, and the record rule is edit access on that item.

## Parameters
- drive_document (integer, path): The DriveDocument's numeric id.
- view (string, optional): Which field set to render.
- X-Request-Id (header, optional): A correlation id of your own. It is recorded in our logs next to the server's request id but never returned: the response header always carries the server's id. A value that does not match the pattern is discarded silently, never rejected.
- If-Match (header, optional): The ETag a write is conditional on. A stale validator is 412 precondition-failed.
- Idempotency-Key (header, optional): A caller-chosen key that makes this POST safe to retry. Replaying it returns the original response with Idempotency-Replayed: true.

## Request body
- operations (array of object ≤ 100, required): The changes, applied in order as one edit: 1 to 100 objects with `op` (`insert_before`, `insert_after`, `replace`, `delete`, `set_checked` or `replace_text`) and `block_id`, plus `version` (the block's, from `?include=blocks`) for a replace or delete, `markdown` for an insert or replace, `checked` for `set_checked`, and `find` and `replace` for `replace_text`.

Unknown keys are refused with `422` validation-failed, naming the key.

## Response 200
- id (integer, required): Id of the document body, not of the drive item it belongs to. The two are numbered separately.
- drive_item_id (integer, required): The drive item this body belongs to. Set on create and immutable afterwards; read the item itself from `GET /api/v2/drive-items/{drive_item}`.
- content (markdown or null, required, detail only): The document body as GitHub-Flavored Markdown: headings, lists, task lists (`- [ ]`), tables, code fences, links, images and formulas (`$…$`) all survive, and the table of contents becomes a list of links to the headings. Detail-only: pass `?view=detail` to get it on the collection. GFM cannot express text colours, highlights, underline, alignment or @mentions: they become plain text. A PATCH of this `content` keeps them in every block you leave unchanged and answers `409` when a block you changed holds them; to change such a block, read `?include=content_extended` and write it back with `format: extended`.
- revision (integer, required): Revision counter, bumped by every change to the body, typing in the editor included. It is the `ETag`'s revision: send the `ETag` back as `If-Match` on a write and a change made since your read answers `412`.
- created_at (timestamp (YYYY-MM-DDThh:mm:ssZ), required): Creation timestamp.
- updated_at (timestamp (YYYY-MM-DDThh:mm:ssZ), required): Last-write timestamp; use for incremental sync. Typing in the collaborative editor moves this, not the drive item's own `updated_at`.
- links (DriveDocumentLinks, required)
  - self (url, required): The canonical URI of this record.
- content_extended (markdown or null, optional, on request): The same document as extended Markdown: GFM plus a notation for what GFM cannot hold, which reads back without loss. Highlight `==text==`, colours `[text]{color=red highlight=blue}` (palette names: gray, brown, orange, yellow, green, blue, purple, pink, red, default), underline `++text++`, `H~2~O`, `x^2^`, formulas `$…$` and `$$…$$`, mentions `@[Name](user:7)`, `#[Name](project:12)`, `%[Name](customer:3)` and `$[Title](document:9)`, the table of contents `[[toc]]`, a paragraph's or heading's background, alignment and indent as `{bg=yellow align=center indent=1}` at its end, and image alignment and caption as `![alt](src "Caption"){align=center}`. Write it back with `format: extended`. `null` when the collaboration server cannot be reached, which is the only renderer that can produce it; retry, or read `content`.
- blocks (array of object or null, optional, on request): The live document as a flat list of blocks in reading order: each top-level block, and within a list each item, nested items after the item they are in. Every block has an id that `POST /api/v2/drive-documents/{drive_document}/actions/edit` addresses, to change one block without sending the rest of the document. `null` when the collaboration server cannot be reached; retry.
- content_html (html or null, optional, on request): The same document as sanitised HTML, preserving the text colours, highlights, alignment and @mentions Markdown cannot carry. Mention spans round-trip unchanged; constructing a new one is out of scope for v2.0.

## Errors
- 403 forbidden-by-policy | insufficient-permission | insufficient-token-scope: Forbidden.
- 409 idempotency-key-in-flight | idempotency-key-reused | state-conflict: Conflict.
- 412 precondition-failed: Precondition failed.
- 415 unsupported-media-type: Unsupported media type.
- 422 unprocessable-relationship | validation-failed: Unprocessable content.
- 400 idempotency-key-required | invalid-cursor | invalid-query-parameter | malformed-request | unsupported-parameter: Bad request.
- 401 token-expired | unauthenticated: Unauthenticated.
- 404 endpoint-not-found | resource-not-found: Not found.
- 406 not-acceptable: Not acceptable.
- 429 rate-limit-exceeded: Too many requests.
- 500 internal-error: Server error.
- 503 tenant-unavailable: Service unavailable.

## Example
```bash
curl -X POST \
  'https://<your-url>/api/v2/drive-documents/1/actions/edit' \
  -H 'Authorization: Bearer <token>' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: <key>' \
  -d '{
    "operations": [
      {
        "op": "set_checked",
        "block_id": "k3j9x2ab",
        "checked": true
      },
      {
        "op": "insert_after",
        "block_id": "h7q2m4zc",
        "markdown": "Agreed on **Monday 09:00**."
      },
      {
        "op": "replace",
        "block_id": "p4n8r2wd",
        "version": "3f9a12c0",
        "markdown": "Room booked for the kick-off."
      }
    ]
  }'
```
