---
id: AnonymizeText
name: Anonymize text
version: 1.0.0
badges:
  - content: Privacy
    backgroundColor: red
    textColor: red
summary: Replaces or transforms detected PII in text using the supplied analysis results and configured anonymization operators.
owners:
  - platform-engineering-team
schemaPath: schema.json
operation:
  method: POST
  path: /anonymize
  statusCodes: ["200", "400", "422"]
sidebar:
  badge: "POST"
---

`AnonymizeText` requests PII transformation from the internal [[service|presidio-api]] Anonymizer sidecar (`POST /anonymize`) using entity spans produced by [[command|AnalyzeText]]. In BookWorm, [[service|chat-api]] and [[service|rating-api]] call this endpoint to replace detected PII spans with `<PII>`.

## Overview

| Property                           | Value                                                            |
| :--------------------------------- | :--------------------------------------------------------------- |
| **Bounded Context**                | Data Privacy (External Integration)                              |
| **Owner Service**                  | [[service\|presidio-api]] (`presidio-anonymizer`)                |
| **Protocol / Format**              | HTTP `POST /anonymize`, `application/json` request and response  |
| **Gateway Endpoint**               | Internal sidecar `POST /anonymize` (not exposed via API Gateway) |
| **Authentication & Authorization** | None (internal service-to-service network boundary)              |
| **Idempotency / Concurrency**      | Stateless and naturally idempotent                               |
| **Rate Limit / Caching**           | None (sidecar)                                                   |
| **Contract Version**               | `1.0.0`                                                          |

:::warning
Pass `analyzer_results` computed against the exact same `text` string. Stale character offsets cause Presidio Anonymizer to corrupt unrelated substrings or reject the request.
:::

## Request & Response Contract

### Request Body (`application/json`)

| Name               | Type       | Required | Constraints                                                                                  | Description                                                                                   |
| :----------------- | :--------- | :------- | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- |
| `text`             | `string`   | Yes      | Exact string analyzed by [[command\|AnalyzeText]]                                            | Original text containing PII spans to transform                                               |
| `analyzer_results` | `object[]` | Yes      | Each item requires `start` (`>= 0`), `end` (`> start`), `score` (`0.0`-`1.0`), `entity_type` | PII detections returned by `POST /analyze`                                                    |
| `anonymizers`      | `object`   | No       | Map of `DEFAULT` or entity type to operator (`replace`, `redact`, `mask`, `hash`, `encrypt`) | Per-entity or fallback operator configuration (BookWorm defaults to `replace` with `"<PII>"`) |

### Success Response (`200 OK`)

| Name    | Type       | Required | Constraints                                                                        | Description                                          |
| :------ | :--------- | :------- | :--------------------------------------------------------------------------------- | :--------------------------------------------------- |
| `text`  | `string`   | Yes      | —                                                                                  | Transformed text after applying configured operators |
| `items` | `object[]` | No       | Each item includes `start`, `end`, `entity_type`, and optional `operator` / `text` | Applied operator metadata                            |

## Behavior & Side Effects

- **Stateless transformation:** Transforms the supplied string in memory and stores no data.
- **Default replacement:** BookWorm configures the `DEFAULT` operator as `{"type": "replace", "new_value": "<PII>"}` for all detected entities.
- **PII logging restriction:** Raw `text` request bodies must never be logged.

## Error Responses

| Status / Code              | Condition                                                          | Client Recovery Action                       |
| :------------------------- | :----------------------------------------------------------------- | :------------------------------------------- |
| `400 Bad Request`          | Invalid request JSON payload                                       | Fix the request body; do not retry unchanged |
| `422 Unprocessable Entity` | Invalid input (e.g., empty text or invalid operator configuration) | Correct the input fields and retry           |

## Related Documentation

- [[service|presidio-api]] — Overview of the Presidio Analyzer and Anonymizer sidecars.
- [[command|AnalyzeText]] — Generate `analyzer_results` spans before calling `AnonymizeText`.
- [[query|GetAnonymizers]] — List supported anonymization operators.

<NodeGraph />

<SchemaViewer file="schema.json" title="Anonymize text schema" maxHeight="500" search="true" />


 ## Raw Schema:schema.json

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"title": "AnonymizeText",
	"description": "Request to transform text using previously detected PII entities.",
	"type": "object",
	"required": ["text", "analyzer_results"],
	"properties": {
		"text": {
			"type": "string",
			"description": "Text to anonymize."
		},
		"anonymizers": {
			"type": "object",
			"description": "Optional operators keyed by DEFAULT or a PII entity type.",
			"additionalProperties": {
				"oneOf": [
					{
						"type": "object",
						"required": ["type", "new_value"],
						"properties": {
							"type": { "const": "replace" },
							"new_value": { "type": "string" }
						}
					},
					{
						"type": "object",
						"required": ["type"],
						"properties": { "type": { "const": "redact" } }
					},
					{
						"type": "object",
						"required": ["type", "masking_char", "chars_to_mask"],
						"properties": {
							"type": { "const": "mask" },
							"masking_char": { "type": "string" },
							"chars_to_mask": { "type": "integer" },
							"from_end": { "type": "boolean" }
						}
					},
					{
						"type": "object",
						"required": ["type"],
						"properties": {
							"type": { "const": "hash" },
							"hash_type": { "type": "string", "enum": ["sha256", "sha512"] }
						}
					},
					{
						"type": "object",
						"required": ["type", "key"],
						"properties": {
							"type": { "const": "encrypt" },
							"key": { "type": "string" }
						}
					}
				]
			}
		},
		"analyzer_results": {
			"type": "array",
			"description": "PII detections returned by the Analyzer.",
			"items": {
				"type": "object",
				"required": ["start", "end", "score", "entity_type"],
				"properties": {
					"start": { "type": "integer" },
					"end": { "type": "integer" },
					"score": { "type": "number" },
					"entity_type": { "type": "string" }
				}
			}
		}
	}
}
