
Pseudonymizing documents by hand does not scale. As soon as you need to process contracts, HR files or data exports before sending them to an AI, a partner or an analytics tool, pseudonymization has to become an automatic step in the flow: an API call.
The minimum viable setup rests on three things: a service that separates pseudonymization domains by application or partner, encrypted transport with strong authentication, and explicit documentation of the mapping table and reversibility, in line with article 4(5) of the GDPR.
This guide covers the endpoints to expect, a step-by-step pipeline, the choice between stateless and stateful processing, authentication, integration examples, a testing strategy, a regulatory checklist and the mistakes to avoid in production.
The golden rule: one pseudonymization domain per application, per partner and per environment. Two systems that share a domain produce the same pseudonym for the same person, which makes their databases linkable.
Key takeaways
| Point | Details |
|---|---|
| Separate the domains | This is the measure that prevents databases from being cross-matched between partners. |
| Choose stateless or stateful before you write code | The choice determines your attack surface and your compliance file. |
| Never pseudonymize headers | Column names must stay intact, or every downstream process breaks. |
| Handle errors on the client side | An ignored error can let clear-text data through without anyone noticing. |
| Document your design choices | That is exactly what the DPO will ask for in the impact assessment. |
Table of contents
- The endpoints to expect
- The pipeline, step by step
- Stateless or stateful?
- Authentication and security
- Deploying the service
- Integration examples
- The testing strategy
- The regulatory checklist
- Good practices and mistakes in production
- The pre-production checklist
- The Safe-doc API
- Frequently asked questions
- Further reading
- Sources
- Recommended reading
The endpoints to expect
| Endpoint | Method | Role |
|---|---|---|
| /pseudonymize | POST | Replaces detected data with pseudonyms |
| /ner | POST | Named entity detection: returns the entities, their type and their position |
| /keys | GET | Lists the available keys per domain |
| /mapping/{id} | GET | Retrieves a mapping table (stateful mode) |
| /health | GET | Monitoring |
| /docs | GET | OpenAPI documentation |
The open-source repository of France's Cour de cassation, the country's highest civil court, which uses it to pseudonymize court decisions, illustrates the detection endpoint: it takes a document ID and its text, and returns the detected entities with their positions.
The parameters to document
| Parameter | Role |
|---|---|
| text or file | The content to process |
| domain | The pseudonymization domain: the key that separates applications or partners |
| variant | The method: deterministic, random or format-preserving |
| key_name | The cryptographic key used |
| Authentication header | Authorization: Bearer <token> or an API key |
Response codes
| Code | Meaning |
|---|---|
| 200 | Processed successfully |
| 202 | Asynchronous job queued |
| 400 | Malformed content or unsupported format |
| 401 | Missing or expired token |
| 403 | Domain not authorized for this client |
| 429 | Quota exceeded |
| 500 | Detection or encryption engine failure |
The pipeline, step by step
Processing starts with preparing the document: check its format (PDF, DOCX, XLSX, CSV, TXT) and its encoding, which should be UTF-8; legacy encodings are converted upstream. The document is then sent to the API, as multipart or base64 depending on the case. For scanned PDFs, optical character recognition extracts the text before any detection. Accepted formats, including scanned PDFs, are listed on the Formats page.
Entity detection combines a named entity recognition model with business rules for known formats: IBANs, social security numbers, company registration numbers, file numbers. Pseudonyms can then take three forms: a random identifier, a deterministic token (HMAC), or a value that preserves the original format, useful for phone numbers or postal codes.
Finally, the client retrieves the result: the pseudonymized document and, in stateful mode or for local restoring, the encrypted mapping table. Each job is logged with its ID, timestamp, domain and a fingerprint of the original document, but never its clear-text content.
curl -X POST https://api.example.com/pseudonymize \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"text": "John Smith, IBAN FR76 3000 6000 0112 3456 7890 189",
"domain": "accounting-client-b",
"variant": "deterministic"
}'
Pro tip: Never pseudonymize the column headers of a CSV or spreadsheet. Process only the cell values: renaming a column breaks every downstream query and import.
Validate structured identifiers with their check algorithm (mod 97 for IBANs, the Luhn check for cards) before pseudonymizing them. That reduces false positives.
Stateless or stateful?
| Criterion | Stateless | Stateful |
|---|---|---|
| Mapping table | None kept on the server | Kept, encrypted |
| Re-identification | Only with the table kept on the client side | Possible through a controlled procedure |
| Use cases | Sending to an outside AI, one-way analyses | Files to archive with possible re-identification |
| Main risk | Permanent loss if the client's table is lost | A table leak means re-identification |
| Compliance | Simpler: no mapping database at the vendor | Contract, restricted access and logging are essential |
Prefer stateless mode whenever confidentiality is critical. A service that keeps nothing reduces your attack surface and simplifies your impact assessment.
Both architectures in detail: Stateless vs. stateful: why zero storage.
Authentication and security
Three levels of authentication are common. An API key is simple, and sufficient for controlled internal environments. OAuth 2.0, with the client credentials flow, is recommended for machine-to-machine integrations in production. Mutual TLS authenticates by certificate for the most demanding environments. Safe-Doc's hosting and security measures are described on the Security page.
In every case: rotate keys regularly (at least every 90 days), store them in a secrets vault, never in code or in versioned environment variables.
Other measures complete the setup: TLS 1.2 at minimum on every endpoint, with HSTS on; mapping tables encrypted at rest; tamper-proof logging of who accessed which domain, when and with what result; and separate environments, with production keys never used in development.
Pro tip: For flows to outside AIs, issue only short-lived tokens (15 to 30 minutes) scoped to the single domain concerned. A compromised token must never give access to every domain.
Deploying the service

If you deploy a pseudonymization API yourself, the pattern is usually the same. Start from the sample environment variables file, then build the image (docker build -t pseudo-api .). Secrets, the encryption key and the hashing key, go in a vault or in a file excluded from version control.
Then start the service with docker compose up -d, and check that /health responds, that the /docs documentation loads, that a test call goes through, and above all that the logs contain no clear-text data.
Send the whole document or extracts?
Sending extracts limits exposure, but makes it harder to detect entities that refer to each other across sentences ("Mr. Smith… he… his employer…"). For legal or HR documents, send the whole document for pseudonymization, then only the useful extracts to the AI tool.
Integration examples
Python:
import requests
response = requests.post(
"https://api.example.com/pseudonymize",
headers={"Authorization": f"Bearer {token}"},
json={"text": document_content, "domain": "hr-internal", "variant": "random"},
timeout=30,
)
response.raise_for_status()
result = response.json()
print(result["pseudonymized_text"])
JavaScript:
const response = await fetch("https://api.example.com/pseudonymize", {
method: "POST",
headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
body: JSON.stringify({ text: documentContent, domain: "legal-client-a", variant: "deterministic" }),
});
if (!response.ok) throw new Error("Pseudonymization failed: " + response.status);
const data = await response.json();
The key point: if there is an error, send nothing downstream. A client that ignores a 500 error and passes the original text to the AI cancels out all the protection.
The testing strategy
Unit tests for the detection engine cover the hard cases: compound names, partial addresses, ambiguous file numbers, spelling variants. Two tests check processing integrity: column headers must be identical before and after, and reversibility is tested by pseudonymizing, restoring, then comparing with the original. Also make sure the table is encrypted and never readable in clear text.
Over time, regression tests replay a set of known examples at each release, and load tests measure latency and error rate under the expected volume. Re-identification tests focus on edge cases, not just the happy path.
Pro tip: In your continuous integration, use only fictitious data, never production data. A test run on real personal data is processing in its own right, with all the obligations that come with it.
The regulatory checklist
The CNIL, France's data protection authority, has published a technical recommendation on the use of APIs (in French) for securely sharing personal data.
Some points are essential. Document the transformations: algorithm, domain, detection model version and the date the rules were last updated. The original database must be kept separate from the pseudonym database, and robustness checked against known re-identification methods (linkage, inference, singling out). And mapping tables are kept only as long as strictly necessary. On the Safe-Doc side, nothing is kept after processing: see the zero data retention (ZDR) page.
Others are strongly recommended: documentation for reusers (update frequency, granularity, formats, pseudonymization measures), a log export the DPO can consult, a reversibility policy specifying who can request re-identification, within what timeframe and with what record, and restricted, logged access to the keys. The reference framework is summarized in our guide to the CNIL and EDPB recommendations.
Pseudonymization reduces the risk; it does not take you out of the GDPR. As long as the table exists, the data remains personal: minimization, limited retention and security still apply.
Good practices and mistakes in production
In production, good practice is simple. Each application, each partner and each environment has its own domain. Each call is logged in a tamper-proof way, and tables are encrypted at rest. Send the API only what needs to be processed, and review the detection rules every time the model is updated. To hand a whole process to an agent, see MCP and pseudonymization.
The common mistakes are the mirror image: pseudonymizing file headers, sharing a domain between two applications, storing mapping tables unencrypted, giving long-lived tokens to AI integrations, not handling errors on the client side, or logging document contents.
Indicators to track: rate of missed entities and false positives, volume and latency per endpoint, confidentiality incidents (unauthorized access to a table, a compromised token).
The pre-production checklist
| Area | Points to check |
|---|---|
| Technical | TLS 1.2 or higher, valid certificate, HSTS; key rotation planned and documented; quotas and rate limiting; mapping tables backed up encrypted, in a separate vault; automatic purge according to the retention policy |
| Governance | Documentation approved by the DPO; data processing agreement signed with the API vendor; re-identification procedure documented and logged; processing added to the records, with an impact assessment if needed |
| Operations | Rollback plan; monitoring and alerts on latency and error rate; escalation procedure for confidentiality incidents |
Document your design choices in the repository: why stateless, why this domain, why this variant. A GDPR audit asks for exactly these justifications, and an up-to-date README is better than a report written under pressure.
The Safe-doc API

The Safe-doc API does one thing: pseudonymize. It accepts text, PDFs, Word files and spreadsheets, returns the pseudonymized text and its mapping table, and does not keep the documents. Large files go through asynchronous processing (create a job, upload, track, retrieve), with consistent aliases across an entire batch.
The same key gives access to the @safedoc/mcp MCP server, for assistants and agents. For a plain text, an agent can also skip the account and the key: it pays for the call in USDC with the x402 protocol (see Safe-Doc for AI agents). The OpenAPI documentation is at app.safe-doc.ai/docs; see also the integrations.
Frequently asked questions
What is a pseudonymization API?
A service that receives a document or text, detects the personal data and replaces it with pseudonyms, returning the result and, if needed, a mapping table to restore it.
What is the difference between stateless and stateful mode?
In stateless mode, the service keeps no table: restoring is only possible with the table kept on the client side. In stateful mode, the table is kept, encrypted, and must be protected accordingly.
Why separate pseudonymization domains?
Because two systems that share a domain produce the same pseudonym for the same person, which allows their databases to be cross-matched.
Which pseudonymization method should you choose?
Random to prevent any linkage; deterministic (HMAC with a secret key) to keep consistency across documents; format-preserving when the downstream system requires a specific format.
Do you need an impact assessment to deploy a pseudonymization API?
The API does not require one on its own, but the processing it serves may: large volumes, sensitive data, sending to an outside AI.
Further reading
- MCP and pseudonymization: finally handing your business processes to AI
- Stateless vs. stateful: which architecture should you choose?
- No storage: CIOs and lawyers, pseudonymize your PDFs and their metadata
Sources
- CNIL: technical recommendation on the use of APIs (in French)
- Cour de cassation: pseudonymization API (open-source repository)
- ENISA: Pseudonymisation techniques and best practices