---
id: AnalyzeText
name: Analyze text
version: 1.0.0
badges:
  - content: Privacy
    backgroundColor: red
    textColor: red
summary: Detects PII entities in one text string or a batch, returning entity types, text offsets, confidence scores, and optional analysis explanations.
owners:
  - platform-engineering-team
schemaPath: schema.json
operation:
  method: POST
  path: /analyze
  statusCodes: ["200"]
sidebar:
  badge: "POST"
---

`AnalyzeText` requests PII detection from the internal [[service|presidio-api]] Analyzer sidecar (`POST /analyze`). In BookWorm, [[service|chat-api]] and [[service|rating-api]] call this endpoint before anonymizing user-supplied text.

## Overview

| Property                           | Value                                                          |
| :--------------------------------- | :------------------------------------------------------------- |
| **Bounded Context**                | Data Privacy (External Integration)                            |
| **Owner Service**                  | [[service\|presidio-api]] (`presidio-analyzer`)                |
| **Protocol / Format**              | HTTP `POST /analyze`, `application/json` request and response  |
| **Gateway Endpoint**               | Internal sidecar `POST /analyze` (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`                                                        |

:::note
The Presidio Analyzer (`presidio-analyzer`) and Anonymizer (`presidio-anonymizer`) run as separate sidecar containers with independent endpoints; never assume a shared base URL.
:::

## Request & Response Contract

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

| Name                      | Type                 | Required | Constraints                                                | Description                                                              |
| :------------------------ | :------------------- | :------- | :--------------------------------------------------------- | :----------------------------------------------------------------------- |
| `text`                    | `string \| string[]` | Yes      | Non-empty string or array of strings                       | Input text to scan for PII entities (BookWorm sends a single `string`)   |
| `language`                | `string`             | Yes      | Two-character ISO 639-1 code (BookWorm defaults to `"en"`) | Language model used for PII recognition                                  |
| `correlation_id`          | `string`             | No       | —                                                          | Caller-supplied correlation identifier echoed for request tracing        |
| `score_threshold`         | `number`             | No       | Default `0.0`; floating-point confidence floor             | Minimum confidence score required to include a detection                 |
| `entities`                | `string[]`           | No       | Valid Presidio entity names                                | Optional allowlist of PII entity types (e.g., `PERSON`, `EMAIL_ADDRESS`) |
| `return_decision_process` | `boolean`            | No       | Default `false`                                            | When `true`, includes recognizer decision-process metadata per detection |
| `ad_hoc_recognizers`      | `object[]`           | No       | Presidio recognizer objects                                | Request-scoped custom pattern or deny-list recognizers                   |
| `context`                 | `string[]`           | No       | —                                                          | Surrounding context words that can boost recognizer confidence           |

### Success Response (`200 OK`)

For a single-string request, returns a JSON array of detection objects. For a batch (`string[]`) request, returns an array of detection arrays (one per input string).

| Name                   | Type      | Required | Constraints                                      | Description                                             |
| :--------------------- | :-------- | :------- | :----------------------------------------------- | :------------------------------------------------------ |
| `entity_type`          | `string`  | Yes      | Presidio entity label                            | Detected PII category (e.g., `PERSON`, `EMAIL_ADDRESS`) |
| `start`                | `integer` | Yes      | `>= 0`                                           | Zero-based inclusive start character index in `text`    |
| `end`                  | `integer` | Yes      | `> start`                                        | Zero-based exclusive end character index in `text`      |
| `score`                | `number`  | Yes      | `0.0`-`1.0`                                      | Confidence score assigned by the recognizer             |
| `analysis_explanation` | `object`  | No       | Present when `return_decision_process` is `true` | Optional recognizer decision metadata                   |

## Behavior & Side Effects

- **Stateless analysis:** Performs in-memory NLP and pattern-based PII detection with no persistent state.
- **Client guard:** BookWorm callers skip calls when `text` is null or whitespace and return the original text unchanged when no detections are returned.
- **PII logging restriction:** Raw `text` payloads and unredacted detection excerpts must never be logged.

## Error Responses

| Status / Code               | Condition                                                                                                | Client Recovery Action                                  |
| :-------------------------- | :------------------------------------------------------------------------------------------------------- | :------------------------------------------------------ |
| `400 Bad Request`           | Malformed request payload or invalid ad-hoc recognizer definition                                        | Fix the request body; do not retry unchanged            |
| `500 Internal Server Error` | Unsupported `language` (`"No matching recognizers were found to serve the request."`) or sidecar failure | Supply a supported ISO 639-1 language code (e.g., `en`) |

## Related Documentation

- [[service|presidio-api]] — Overview of the Presidio Analyzer and Anonymizer sidecars.
- [[command|AnonymizeText]] — Transform text using detections returned by `AnalyzeText`.
- [[query|GetRecognizers]] — List active Presidio Analyzer recognizers.
- [[query|GetSupportedEntities]] — List detectable PII entity types.

<NodeGraph />

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


 ## Raw Schema:schema.json

{
	"$schema": "https://json-schema.org/draft/2020-12/schema",
	"title": "AnalyzeText",
	"description": "Request to detect PII in one or more text strings.",
	"type": "object",
	"required": ["text", "language"],
	"properties": {
		"text": {
			"description": "Text to analyze, as a single string or a batch of strings.",
			"oneOf": [{ "type": "string" }, { "type": "array", "items": { "type": "string" } }]
		},
		"language": {
			"type": "string",
			"description": "Two-character ISO 639-1 language code.",
			"examples": ["en"]
		},
		"correlation_id": { "type": "string" },
		"score_threshold": {
			"type": "number",
			"description": "Minimum detection confidence score."
		},
		"entities": {
			"type": "array",
			"items": { "type": "string" },
			"description": "PII entity types to analyze."
		},
		"return_decision_process": {
			"type": "boolean",
			"description": "Whether to include analysis explanations in the response."
		},
		"ad_hoc_recognizers": {
			"type": "array",
			"items": { "type": "object" },
			"description": "Request-specific recognizers."
		},
		"context": {
			"type": "array",
			"items": { "type": "string" },
			"description": "Context words that can improve recognition confidence."
		}
	}
}
