# Edit text document

Change exact text in a collaborative document. Supply the revision you read to reject intervening changes.

POST https://api.brigg.app/v1/operations/documents.EditTextDocument

## Access & visibility

Allow `documents.EditTextDocument` on your API key.

**Workspace access by default.** Private member data requires [approved member delegation](https://developer.brigg.app/authentication#member-delegation) through `Brigg-Act-As`; the key supplies permissions while private ownership and project boundaries remain enforced.

[Set up authentication](https://developer.brigg.app/authentication) · [Choose permissions](https://developer.brigg.app/permissions)

## Request fields

Send a JSON object with the following fields. Required fields must be included; omit optional fields you do not need.
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `file_id` | string | Yes | Use the file_id of a collaborative text document. Find an existing document with [ListDocuments](https://developer.brigg.app/reference/documents/ListDocuments) and select kind=text_document. An uploaded PDF, Word file or plain-text file is not a collaborative text document. [documents.CreateTextDocument](https://developer.brigg.app/reference/documents/CreateTextDocument). At least 1 character. |
| `old_string` | string | Yes | Exact text from a current ReadTextDocument response. By default it must occur exactly once. At least 1 character. |
| `new_string` | string | Yes | Text to replace the matched passage. An empty string removes it. |
| `replace_all` | boolean | No | Defaults to false. True replaces every exact match; it does not interpret a regular expression. |
| `expected_revision` | string | No | Copy revision from the latest ReadTextDocument response. A concurrent change returns 409 revision_conflict without applying this edit. Re-read, reconcile and submit a new request with a new idempotency key. Omit only when intentionally editing the current content regardless of prior changes. At least 1 character. At most 200 characters. |

## Work with text and saved versions

All documents use a stable `file_id`. Select `document_kind=text_document` from the listing for these collaborative text operations. [Read text document](https://developer.brigg.app/reference/documents/ReadTextDocument) returns its current Markdown and location.

For an exact change, use [Edit text document](https://developer.brigg.app/reference/documents/EditTextDocument) with the existing text and its replacement; this avoids sending an old full copy over another edit. [Replace text document](https://developer.brigg.app/reference/documents/ReplaceTextDocument) replaces the entire Markdown body. Send the read response’s `revision` as `expected_revision` to refuse intervening changes atomically. Re-read before resolving a failed match or revision conflict.

A saved `version_id` identifies historical content. List versions before reading or reverting one, and use [Checkpoint text document](https://developer.brigg.app/reference/documents/CheckpointTextDocument) when you need a named saved point. A revert changes current content; it is not just a historical read.

## Response

Returns **200 OK** with a JSON body.
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `file_id` | string | Yes | The same stable identity supplied as file_id. This response uses camelCase; later requests still use file_id. |
| `filename` | string | Yes | Current document name. A collaborative text document is not an uploaded PDF or Word file and does not require a filename extension. |
| `scope` | string or null | Yes | Current document collection: org is workspace-shared, user is personal, and resources is the resources collection. Null means no collection is recorded; it does not grant access. This is location metadata, not a request to move the document. |
| `path` | string | Yes | Folder path within the current collection. An empty string is the collection root. |
| `word_count` | number | Yes | Word count of the returned or saved text, excluding Markdown formatting. |
| `revision` | string | Yes | Opaque token identifying this exact content. Pass it as expected_revision to a text edit. It is not a history version_id and cannot be used to select an export version. |
| `version_id` | string or null | Yes | Version ID of the resulting content, not a backup of the previous text. An automatic save returns null when the content matches the stored projection and no new version is needed. Null is not an empty document or a failed edit. ListTextDocumentVersions discovers saved versions; keep each version_id together with its file_id. |
| `replacements` | number | Yes | Number of matching passages changed by this edit; this is a result count, not a list of edits. |

## Errors & retries

Set `BRIGG_REQUEST_ID` once for each logical action. The samples send it as `Idempotency-Key`. Reuse the same value and body on retries, including after a timeout; a missing response does not prove the action failed.

For rate limits, follow the server’s retry guidance and back off. See [HTTP errors](https://developer.brigg.app/http#errors) and [safe retries and limits](https://developer.brigg.app/reliability).

| HTTP status | Code | What to do |
| --- | --- | --- |
| 400 | `invalid_json` | Send a JSON object with Content-Type: application/json. |
| 400 | `invalid_input` | Check the request fields and types. Supply a stable Idempotency-Key containing 1–200 characters. |
| 401 | `invalid_key` | The workspace API key is missing, invalid or revoked. |
| 403 | `forbidden` | Check the key’s operation and resource grants. If Brigg-Act-As is supplied, the key must be authorized to delegate to that member. |
| 404 | `not_found` | The requested operation or resource is not available to this credential. |
| 429 | `rate_limited` | Wait for Retry-After before retrying. Reuse the original Idempotency-Key. |
| 409 | `not_text_document` | This file is not a collaborative text document. Use CreateTextDocument or select kind=text_document from ListDocuments. |
| 409 | `revision_conflict` | The live content changed since expected_revision. No edit was applied. Re-read, reconcile your change and use a new idempotency key. |
| 409 | `not_found` | old_string does not occur in the current text. ReadTextDocument again and prepare a new edit. |
| 409 | `not_unique` | old_string has more than one match. Inspect details.occurrences; choose a unique passage or deliberately use replace_all. |
| 409 | `unchanged` | The replacement does not change the text. Do not retry this edit unchanged. |

## Next steps

- [Read text document](https://developer.brigg.app/reference/documents/ReadTextDocument)
- [Replace text document](https://developer.brigg.app/reference/documents/ReplaceTextDocument)
- [List text document versions](https://developer.brigg.app/reference/documents/ListTextDocumentVersions)
- [Create text document](https://developer.brigg.app/reference/documents/CreateTextDocument)

[Download OpenAPI](https://developer.brigg.app/openapi.json) · [Versioning & retirement](https://developer.brigg.app/versioning)

## Examples

### Change one passage

Read the current document first. This changes Tuesday to Wednesday once.
#### cURL


```sh
curl 'https://api.brigg.app/v1/operations/documents.EditTextDocument' \
  -H "Authorization: Bearer $BRIGG_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $BRIGG_REQUEST_ID" \
  --data-raw '{
  "file_id": "f_project_notes",
  "old_string": "Tuesday",
  "new_string": "Wednesday",
  "expected_revision": "tdr_before_edit"
}'
```

#### TypeScript


```typescript
const requestId = process.env.BRIGG_REQUEST_ID;
if (!requestId) throw new Error("Set BRIGG_REQUEST_ID once per action and reuse it on retries.");

const response = await fetch("https://api.brigg.app/v1/operations/documents.EditTextDocument", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.BRIGG_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": requestId, // Create once per action; reuse on retries.
  },
  body: JSON.stringify({
    "file_id": "f_project_notes",
    "old_string": "Tuesday",
    "new_string": "Wednesday",
    "expected_revision": "tdr_before_edit"
  }),
});
const result = await response.json();
if (!response.ok) throw new Error(`${response.status}: ${result.error} — ${result.message}`);
console.log(result);
```

#### Python


```python
import json
import os
from urllib.request import Request, urlopen
from urllib.error import HTTPError

request_id = os.environ["BRIGG_REQUEST_ID"]  # Reuse for retries of this action.
payload = {
  "file_id": "f_project_notes",
  "old_string": "Tuesday",
  "new_string": "Wednesday",
  "expected_revision": "tdr_before_edit"
}
request = Request(
    "https://api.brigg.app/v1/operations/documents.EditTextDocument",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {os.environ['BRIGG_API_KEY']}",
        "Content-Type": "application/json",
        "Idempotency-Key": request_id,  # Create once per action; reuse on retries.
    },
    method="POST",
)
try:
    with urlopen(request) as response:
        print(json.load(response))
except HTTPError as error:
    print(error.code, json.load(error))
    raise
```

#### Response example


```json
{
  "file_id": "f_project_notes",
  "filename": "Project notes",
  "scope": "org",
  "path": "Projects",
  "word_count": 7,
  "revision": "tdr_after_edit",
  "version_id": "tdv_project_notes_2",
  "replacements": 1
}
```

## JSON schemas


```json-schema-request
{
  "type": "object",
  "properties": {
    "file_id": {
      "type": "string",
      "minLength": 1,
      "description": "Use the file_id of a collaborative text document. Find an existing document with [ListDocuments](https://developer.brigg.app/reference/documents/ListDocuments) and select kind=text_document. An uploaded PDF, Word file or plain-text file is not a collaborative text document. [documents.CreateTextDocument](https://developer.brigg.app/reference/documents/CreateTextDocument)."
    },
    "old_string": {
      "type": "string",
      "minLength": 1,
      "description": "Exact text from a current ReadTextDocument response. By default it must occur exactly once."
    },
    "new_string": {
      "type": "string",
      "description": "Text to replace the matched passage. An empty string removes it."
    },
    "replace_all": {
      "type": "boolean",
      "description": "Defaults to false. True replaces every exact match; it does not interpret a regular expression."
    },
    "expected_revision": {
      "type": "string",
      "minLength": 1,
      "maxLength": 200,
      "description": "Copy revision from the latest ReadTextDocument response. A concurrent change returns 409 revision_conflict without applying this edit. Re-read, reconcile and submit a new request with a new idempotency key. Omit only when intentionally editing the current content regardless of prior changes."
    }
  },
  "required": [
    "file_id",
    "old_string",
    "new_string"
  ],
  "additionalProperties": false,
  "examples": [
    {
      "file_id": "f_project_notes",
      "old_string": "Tuesday",
      "new_string": "Wednesday",
      "expected_revision": "tdr_before_edit"
    }
  ]
}
```


```json-schema-response
{
  "type": "object",
  "properties": {
    "file_id": {
      "type": "string",
      "description": "The same stable identity supplied as file_id. This response uses camelCase; later requests still use file_id."
    },
    "filename": {
      "type": "string",
      "description": "Current document name. A collaborative text document is not an uploaded PDF or Word file and does not require a filename extension."
    },
    "scope": {
      "type": [
        "string",
        "null"
      ],
      "description": "Current document collection: org is workspace-shared, user is personal, and resources is the resources collection. Null means no collection is recorded; it does not grant access. This is location metadata, not a request to move the document."
    },
    "path": {
      "type": "string",
      "description": "Folder path within the current collection. An empty string is the collection root."
    },
    "word_count": {
      "type": "number",
      "description": "Word count of the returned or saved text, excluding Markdown formatting."
    },
    "revision": {
      "type": "string",
      "description": "Opaque token identifying this exact content. Pass it as expected_revision to a text edit. It is not a history version_id and cannot be used to select an export version."
    },
    "version_id": {
      "type": [
        "string",
        "null"
      ],
      "description": "Version ID of the resulting content, not a backup of the previous text. An automatic save returns null when the content matches the stored projection and no new version is needed. Null is not an empty document or a failed edit. ListTextDocumentVersions discovers saved versions; keep each version_id together with its file_id."
    },
    "replacements": {
      "type": "number",
      "description": "Number of matching passages changed by this edit; this is a result count, not a list of edits."
    }
  },
  "required": [
    "file_id",
    "filename",
    "scope",
    "path",
    "word_count",
    "revision",
    "version_id",
    "replacements"
  ],
  "additionalProperties": false,
  "examples": [
    {
      "file_id": "f_project_notes",
      "filename": "Project notes",
      "scope": "org",
      "path": "Projects",
      "word_count": 7,
      "revision": "tdr_after_edit",
      "version_id": "tdv_project_notes_2",
      "replacements": 1
    }
  ]
}
```

