How to Detect PII in Text with an API
Use a PII detection API to scan user input, logs, and LLM context. Request format, response fields, verdict semantics, and integration patterns.
You detect PII in text with an API by sending the raw string to a dedicated scanning endpoint, receiving structured findings with categories and character offsets, and branching your application logic on the returned verdict before the text is logged or forwarded to an LLM. An API-based approach keeps detection rules maintained centrally, avoids shipping large pattern libraries in every client, and gives you consistent verdict semantics across services written in different languages.
When an API beats an embedded library
Teams choose a PII detection API when:
- Multiple services (Node.js APIs, Python workers, serverless functions) need the same ruleset
- You want detection updates without redeploying every microservice
- You need audit-friendly responses (
request_id, structuredfindings) for security reviews - LLM preprocessing runs on infrastructure that should stay thin
For language-specific integration examples, see PII Detection in Node.js and PII Detection in Python. For conceptual background, start with What Is PII Detection?.
IdenticAPI endpoint overview
Endpoint: POST /api/v1/security/pii-secrets
Authentication: Include your API key in the Authorization header as documented in PII & Secrets Detection docs.
Request body:
{
"text": "Contact user@example.com or call 555-010-0200.",
"redact": false
}
| Field | Type | Required | Description |
|---|---|---|---|
text | string | Yes | Text to scan (1–32,000 characters) |
redact | boolean | No | When true, response includes redacted_text with placeholders |
Example response (detection only):
{
"request_id": "req_xyz789",
"api": "pii-secrets-detection",
"verdict": "suspicious",
"risk": "medium",
"confidence": 0.95,
"findings": [
{
"category": "email",
"reason": "Detected email (pii)",
"confidence": 0.95,
"start": 8,
"end": 24
},
{
"category": "phone",
"reason": "Detected phone (pii)",
"confidence": 0.8,
"start": 33,
"end": 45
}
],
"reasons": [
"Detected email (pii)",
"Detected phone (pii)"
],
"usage_units": 1,
"processing_time_ms": 6,
"detector_version": "1.0.0"
}
Example response with redaction ("redact": true):
{
"verdict": "suspicious",
"findings": [ "..."],
"redacted_text": "Contact [EMAIL] or call [PHONE]."
}
Explore the product overview at PII & Secrets Detection or paste sample strings into the PII Checker without writing code first.
Verdict semantics
Understanding verdicts keeps your error handling predictable:
| Verdict | Risk level | Meaning | Suggested action |
|---|---|---|---|
safe | low | No PII or secrets detected | Proceed |
suspicious | medium | PII detected (email, phone, SSN, etc.) | Redact, warn, or block per policy |
unsafe | high | Secrets detected (API keys, private keys, tokens) | Block and rotate credentials if exposed |
Secrets elevate the verdict to unsafe even when PII is also present. Treat unsafe as a hard stop for LLM forwarding unless you have an explicit exception process.
Detected categories
PII types include email, phone, credit_card, iban, ipv4, and ssn.
Secret types include private_key, stripe_key, aws_access_key, github_token, openai_key, bearer_token, credential_pair, and others listed in the documentation.
Credit card detection applies Luhn validation to reduce false positives on arbitrary digit strings. For a deeper dive on card-number scanning, see Detecting Credit Card Numbers Without Excessive False Positives.
Integration patterns
Pre-LLM gate (recommended)
User input → PII API scan → [redact | block | allow] → LLM provider
Call the API synchronously in your chat handler. If verdict is suspicious and your policy requires redaction, resubmit with "redact": true or redact client-side using findings offsets.
Batch document ingestion
For RAG pipelines, scan each chunk before embedding:
Document → chunker → for each chunk: PII API → redacted chunk → embedder
Batch jobs should handle rate limits and retries. Log request_id values for chunks that triggered findings so compliance teams can audit later.
Log sanitizer sidecar
A log forwarding agent can call the API on each log line or on aggregated buffers. This pattern adds latency; use sampling or async queues for high-volume systems.
Unified guard orchestration
If you also screen for prompt injection or moderate output, combine checks in a single pre-flight step. PII scanning pairs naturally with injection detection because both operate on untrusted text entering the model.
Example: cURL request
curl -X POST "https://www.identicapi.com/api/v1/security/pii-secrets" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Ship to user@example.com. Payment: 4111111111111111",
"redact": true
}'
Use synthetic values in tests and documentation—never paste production credentials or real customer data into examples.
Handling findings in application code
A robust handler typically:
- Parses
findingsand groups bycategory - Maps
verdictto an internal enum (ALLOW,REDACT,BLOCK) - Stores
request_idwith the conversation record for traceability - Never logs the raw
textfield whenverdictis notsafe - Surfaces user-friendly messages when blocking ("Please remove payment details from your message")
When redacting, prefer the API's redacted_text field for consistency with placeholder tokens like [EMAIL] and [CREDIT_CARD]. If you build custom placeholders, document the mapping so downstream parsers stay aligned.
Testing your integration
Build a fixture file with synthetic cases:
| Input snippet | Expected category | Expected verdict |
|---|---|---|
user@example.com | email | suspicious |
555-010-0200 | phone | suspicious |
sk-test_abcdefghijklmnopqrstuvwxyz123456 | stripe_key | unsafe |
Hello, how can I help? | (none) | safe |
Run these in CI against your staging API key. Complement API tests with manual checks via the PII Checker.
Performance and cost considerations
Each IdenticAPI request consumes one usage unit. For chat applications, one scan per user message is usually sufficient. RAG ingestion may scan thousands of chunks—budget accordingly or sample high-risk document types first.
The 32,000-character limit means very large payloads should be split at sentence or paragraph boundaries before scanning. Avoid splitting mid-token (e.g., splitting user@example.com across two requests).
Limitations
API-based regex detection:
- May miss obfuscated or non-standard formats
- Can flag test data that matches production patterns
- Does not classify whose PII was found or whether processing is lawful
- Adds network latency compared to in-process libraries
Configure timeouts and fallbacks explicitly. Common policies:
- Fail closed — Block the LLM call if the scanner is unavailable (strongest privacy posture)
- Fail open with alert — Allow the request but page on-call (lower friction, higher risk)
Document whichever policy you choose; neither is universally correct.
Related reading
Frequently asked questions
What is the IdenticAPI endpoint for PII detection?
Send POST /api/v1/security/pii-secrets with a JSON body containing text (required, 1–32,000 characters) and an optional redact boolean. Authenticate with your API key in the Authorization header.
What fields are in the API response?
Responses include request_id, api, verdict, risk, confidence, findings (with category, reason, confidence, start, end), reasons, usage_units, processing_time_ms, and detector_version. When redact is true and findings exist, redacted_text is also returned.
Should I call the API from the browser or the server?
Always call from your server. Client-side scanning exposes your API key and can be bypassed by direct API calls to your backend. Place the scan in the same request path that constructs the LLM payload.
How do I handle scanner downtime in production?
Define an explicit policy: fail closed (block LLM calls) for high-assurance apps, or fail open with alerting for lower-risk channels. Document the choice and test failover behavior.
Related reading
- What Is PII Detection?
PII detection identifies personally identifiable information in text — emails, phone numbers, government IDs, and more. …
- PII Detection in Node.js
Integrate PII and secrets detection in Node.js — server-side API calls, redaction options, and placement in Express or N…
- PII Detection in Python
Call IdenticAPI PII detection from Python backends — authentication, request payloads, redaction, and error handling for…