Blog

Document pseudonymization API: guide for developers and CISOs

Elegant cover illustration for the pseudonymization API user guide

To pseudonymize documents via an API in France, the minimum viable configuration rests on three elements: a service that separates pseudonymization domains by application, encrypted transport (TLS 1.2+) with strong authentication, and explicit documentation of mapping and reversibility compliant with Article 4(5) of the GDPR. Choose stateless mode if you do not need subsequent re-identification; opt for stateful mode only if your use case requires it, with encrypted mapping and logged access.

The essential references for this implementation are the CNIL technical recommendation on secure data sharing via API, the open-source repository Cour-de-cassation/pseudonymisation-api, the Teavaro product documentation, and the French SaaS solution Safe-doc.

  • Verify that your endpoints expose at minimum `/pseudonymise` and `/ner`.
  • Enable TLS on all calls, without exception.
  • Define a distinct domain per application or partner.
  • Decide on stateless or stateful mode before coding the pipeline.

Pro tip: If you need cross-analysis without re-identification, prefer deterministic pseudonymization with a separate domain per partner. An HMAC-SHA256 or Format-Preserving Encryption (FPE) construct lets you join datasets without ever exposing the clear identifier.


Key points

PointDetails
Domain separationA distinct domain per application prevents database overlap between partners.
Architecture choiceStateless if no re-identification; stateful with AES-256-GCM encrypted mapping if necessary.
CNIL checklistDocument transformations, separate bases, verify robustness against re-identification.
AuthenticationOAuth 2.0 or mTLS in production, short-lived tokens for external LLMs.
Safe-docStateless REST API, detection of 90+ PII types, PDF audit export, zero document storage.

Table of contents

What endpoints, parameters and response formats to expect from a pseudonymization API?

Document pseudonymization APIs typically expose a set of standardized endpoints; knowing them saves you from reinventing the wheel with each integration.

Common endpoints

EndpointMethodRole
`/pseudonymise`POSTReplaces detected PII with pseudonyms (UUID, token, FPE value)
`/ner`POSTNamed entity recognition; returns JSON with labels and positions
`/keys`GETLists pseudonymization keys available by domain
`/variants`GETReturns configured pseudonymization variants
`/fhir/$de-identify`POSTDe-identification of FHIR resources (healthcare)
`/fhir/$de-pseudonymize`POSTControlled re-identification of FHIR resources

API endpoint diagram showing the methods used and associated user roles

The Cour-de-cassation/pseudonymisation-api repository concretely illustrates the `/ner` endpoint: it receives a `Decision { idDocument, text }` object and returns a JSON listing the detected entities with their positions, accompanied by a human verification checklist for ambiguous cases. The Teavaro documentation demonstrates a `/pseudonymise` endpoint that directly returns the pseudonymized value, for example `{ "pemail": "550e8400-e29b-41d4-a716-446655440000" }`, ready to replace the original PII.

Essential parameters to document

  • `resource` / `payload`: the document or string to pseudonymize.
  • `domain`: identifier of the pseudonymization domain (separation key per partner).
  • `key_name`: name of the cryptographic key to use.
  • `variant`: pseudonymization variant (deterministic, random, FPE).
  • `settings`: additional options, for example `domain-prefix` to prefix pseudonyms.
  • Authentication headers: `Authorization: Bearer <token>` or `X-API-Key: <key>`.

HTTP codes and error handling

Common statuses are `200 OK` (successful synchronous processing), `202 Accepted` (asynchronous processing queued), `400 Bad Request` (malformed payload or unsupported format), `401 Unauthorized` (token missing or expired), `403 Forbidden` (domain not authorized) and `500 Internal Server Error` (NER or cryptographic engine failure). For large files, favor streaming mode or pagination by blocks of pages rather than a monolithic upload.

Domain separation is not just a technical parameter: it is a governance requirement. Two partners using the same domain generate the same pseudonym for the same individual, which creates a risk of database overlap. The CNIL recommendation explicitly insists on this separation to prevent indirect re-identification.


How to pseudonymize a document via an API, step by step

The complete pipeline follows seven sequential steps. Here is how to chain them in production.

1. Prepare the document. Verify the format (PDF, DOCX, XLSX, CSV, TXT) and encoding (UTF-8 recommended). The maximum accepted size varies by service; typically allow 10-50 MB per file.

2. Upload the document. Send the file via a multipart POST or in base64 depending on the API specification.

```bash

curl -X POST https://api.example.com/upload \

-H "Authorization: Bearer $TOKEN" \

-F "file=@contrat.pdf" \

-F "domain=juridique-client-a"

```

3. Trigger OCR extraction if needed. For scanned PDFs, the API launches an OCR step before NER detection. Some services integrate it automatically; others expose a separate `/ocr` endpoint.

4. Launch NER detection and business rules. The API identifies entities (names, company IDs, IBANs, addresses, dates) via a NER model and configurable rules. The enki-run/shield project combines spaCy and Presidio with customizable rules, while keeping CSV/XLSX column headers intact.

5. Generate pseudonyms. Depending on the configuration, the replacement value is a random UUID, a deterministic HMAC token, or an FPE value compliant with RFC 5297 that preserves the original format (useful for phone numbers or postal codes).

6. Retrieve the pseudonymized document and mapping. The API returns the processed document and, if stateful mode is enabled, an encrypted mapping `{ pseudonym: original_value }` to keep on your side.

```bash

curl -X POST https://api.example.com/pseudonymise \

-H "Authorization: Bearer $TOKEN" \

-H "Content-Type: application/json" \

-d '{"document_id": "doc-123", "domain": "juridique-client-a", "variant": "deterministic"}'

```

7. Log and export the mapping. Record the processing identifier, timestamp, domain and hash of the original document. Export the encrypted mapping to a vault separate from the production database.

Supported formats and technical limits

  • PDF (native and scanned with OCR), DOCX, XLSX, CSV, TXT are the most common formats.
  • XLSX and CSV files: column headers should never be pseudonymized.
  • Encoding constraint: UTF-8 mandatory for text files; legacy encodings (ISO-8859-1) must be converted upstream.

Pro tip: Always keep CSV/XLSX column headers unchanged. Pseudonymizing column names breaks the compatibility of all your downstream pipelines, from SQL queries to BI imports. Process only cell values.


Authentication, security and architecture choice: stateless or stateful?

The choice between stateless and stateful determines both your GDPR posture and your attack surface.

Stateless vs stateful: practical implications

In stateless mode, the API retains no mapping after processing. The pseudonymized document is returned immediately, without server-side persistence. Re-identification becomes impossible unless the client keeps the mapping itself. This is the recommended architecture for external LLM processing and cases where re-identification is never necessary.

Re-identification remains possible via a controlled, logged, and restricted-access procedure. The eHealth cookbook describes an advanced method based on ECC and blinding: neither the client nor the central service can alone reconstruct the clear identifier without a joint procedure.

CriterionStatelessStateful
Mapping storageNone server-sidePersisted (encrypted)
Re-identificationImpossible without client mappingPossible via controlled procedure
Recommended use caseExternal LLMs, analyses without re-identificationMedical records, legal with archiving
Main riskDefinitive loss if client mapping lostMapping leak = re-identification
GDPR complianceSimplified (no mapping database)Requires DPA, restricted access, logging

Authentication options

  • API key (`X-API-Key`): simple to implement, sufficient for controlled internal environments.
  • OAuth 2.0 (client credentials): recommended for machine-to-machine integrations in production.
  • mTLS: mutual authentication by certificate, for high-security environments.

Whichever option you choose, implement regular key rotation and store them in a secret vault (HashiCorp Vault, AWS Secrets Manager or equivalent). Access tokens should have a short lifetime, especially for processing involving external LLMs.

Mandatory complementary measures

  • TLS 1.2 minimum on all endpoints, with HSTS enabled.
  • Encryption at rest of mappings in AES-256-GCM (as enki-run/shield does).
  • Immutable access logging: who accessed which domain, when, with what result.
  • Environment separation: never use production keys in development.

Pro tip: For processing via external LLMs (ChatGPT, Claude), grant only short-lived tokens (15-30 minutes maximum) and limit their scope to the single domain concerned. A compromised token must never grant access to all pseudonymization domains.


CNIL and GDPR checklist for using a pseudonymization API in France

The CNIL technical recommendation on secure data sharing via API sets precise requirements that any deployment in France must respect.

Mandatory points

  • Document the applied transformations: algorithm, domain, NER model version, rule update date.
  • Physically or logically separate the source database of raw data from the pseudonym database.
  • Verify the robustness of the process against known re-identification methods (cross-referencing attacks, inference, singling-out).
  • Define a minimal retention policy: keep mappings only for the strictly necessary time.

Strongly recommended points

  • Provide re-users with documentation describing the update frequency, data granularity, formats, historical depth and pseudonymization measures applied.
  • Implement an export of audit logs in PDF or structured format, accessible by the DPO.
  • Define an explicit reversibility policy: who can request re-identification, within what timeframe, with what traceability.
  • Restrict access to decryption keys and log each use.

Pseudonymization under Article 4(5) of the GDPR does not exempt from respecting the principles of minimization and storage limitation. It reduces residual risk, but pseudonymized data remains personal data as long as the mapping exists. The CNIL recommendation recalls that database separation is the most effective organizational measure to limit this risk.

The Etalab guides on pseudonymization complement this framework with French best practices for shared data governance, particularly on documentation of methods and traceability of transformations.

For teams managing sensitive documents within the meaning of Article 4(5) of the GDPR, Safe-doc's GDPR pseudonymization page details the legal distinctions between anonymization and pseudonymization and their practical implications for documentation.


CNIL and GDPR checklist for using a pseudonymization API in France - overview diagram

Integration examples and tests: curl, JavaScript and Python

Ready-to-use snippets

curl

```bash

Pseudonymization of a text document

curl -X POST https://api.example.com/pseudonymise \

-H "Authorization: Bearer $TOKEN" \

-H "Content-Type: application/json" \

-d '{

"text": "Jean Dupont, IBAN FR76 3000 6000 0112 3456 7890 189",

"domain": "comptabilite-client-b",

"variant": "deterministic"

}'

Expected response:

{ "pseudonymised_text": "PERS_001, IBAN XXXX_001", "mapping_id": "map-abc123" }

```

JavaScript (fetch)

```javascript

const response = await fetch('https://api.example.com/pseudonymise', {

method: 'POST',

headers: {

'Authorization': `Bearer ${token}`,

'Content-Type': 'application/json'

},

body: JSON.stringify({

text: documentContent,

domain: 'juridique-client-a',

variant: 'deterministic'

})

});

const data = await response.json();

console.log(data.pseudonymised_text);

```

Python (requests)

```python

import requests

response = requests.post(

'https://api.example.com/pseudonymise',

headers={'Authorization': f'Bearer {token}'},

json={

'text': document_content,

'domain': 'rh-interne',

'variant': 'random'

}

)

result = response.json()

print(result['pseudonymised_text'])

```

Automated testing strategy

1. Header non-translation tests: verify that CSV/XLSX column names are identical before and after processing.

2. Reversibility tests (if enabled): pseudonymize a value, re-identify it, compare with the original.

3. Encrypted mapping assertion: verify that the returned mapping is properly encrypted (not readable in clear text).

4. Basic load tests: send 50 concurrent requests and measure average latency and error rate.

5. NER regression tests: maintain a set of fixtures with known entities and verify that the detection rate does not regress between versions.

Pro tip: In your CI/CD pipeline, use exclusively anonymized fixtures (never real production data) and simulate separate domains for each test environment. A test that passes in production with real PII data is a potential GDPR violation, even in a testing context.

Checklist before going to production

  • Document format verified and UTF-8 encoding confirmed.
  • HTTP 400/401/403/500 error handling implemented on the client side.
  • Quotas and rate-limiting documented and tested.
  • API SLA verified and latency alerts configured.

Best practices and common mistakes to avoid in production

Best practices

  • Assign a distinct domain per application, per partner and per environment (dev/staging/prod).
  • Enable immutable logging: each call must trace the request identifier, domain, timestamp and result.
  • Systematically encrypt mappings at rest in AES-256-GCM.
  • Minimize data sent to the API: send only the necessary fields, not the entire document if only a section contains PII.
  • Regularly review NER rules and detection patterns, at least with each update of the underlying language model.

Common mistakes

  • Pseudonymizing file headers: breaks all downstream pipelines that rely on column names.
  • Forgetting domain separation: two applications sharing the same domain can overlap their pseudonym databases.
  • Storing mappings without encryption: a clear mapping is a direct re-identification database.
  • Using long-lived tokens for external LLMs: Shadow AI feeds precisely on this type of uncontrolled access.
  • Not testing error handling: an API that returns 500 without the client handling it can silently let non-pseudonymized PII through.

Domain separation directly reduces the risk of database overlap, a point that the CNIL recommendation identifies as the priority organizational measure to limit indirect re-identification.

Operational indicators to monitor

  • NER error rate (missed entities or false positives).
  • Volume of requests per second and average latency per endpoint.
  • Number of confidentiality incidents declared (unauthorized mapping access, compromised token).

Pro tip: Document design decisions in your repository (why stateless rather than stateful, why this domain, why this variant). A GDPR audit requires precisely these justifications. A well-maintained README is worth more than a report drafted after the fact under pressure.


Technical and audit checklist before going to production

Technical controls

1. TLS 1.2+ enabled on all endpoints, valid certificate and HSTS configured.

2. API key rotation scheduled (at least every 90 days) and procedure documented.

3. Rate-limiting and quotas configured to prevent abuse and overload.

4. Backup of encrypted mappings in a vault separate from the production database.

5. Automatic purging of mappings according to the defined retention policy.

GDPR controls and governance

  • Documentation for re-users written and validated by the DPO.
  • DPA (data processing agreement) signed with the API provider.
  • Mapping retention rules defined and implemented.
  • Temporary re-identification procedure documented, logged and with restricted access.

Tests required before launch

  • Integration tests covering PDF, DOCX, CSV formats and error cases.
  • Load tests validating performance under expected production volume.
  • Security review (pentest or code review) on exposed endpoints.
  • Log audit: verify that each call is traced and that logs are immutable.
  • Generation of an auditability PDF report and verification of its completeness.

Operations

  • Rollback plan documented in case of API failure.
  • API SLA verified and availability alerts configured.
  • Monitoring of main endpoints with alert thresholds on latency and error rate.
  • Escalation procedure in case of a confidentiality incident.

What the usual guides don't tell you about pseudonymization via API

Most articles on pseudonymization via API stop at the list of endpoints and a curl snippet. This is insufficient for a serious deployment.

The real risk is not technical: it is organizational. Teams that correctly implement TLS and OAuth 2.0, but share a single pseudonymization domain across five applications, create a cross-referencing graph that any analyst can exploit. Domain separation is the most underestimated measure in the entire architecture.

The other blind spot concerns Shadow AI. When a collaborator copies and pastes a contract into ChatGPT without going through a pseudonymization layer, it is not a network security problem: it is a governance problem that the API alone does not solve. The API must be coupled with an access policy and short-lived tokens for the protection to be real.

Finally, stateless mode is often presented as "simpler." It is technically simpler, but it transfers mapping responsibility to the client. If this mapping is lost, re-identification becomes definitively impossible, which can pose legal problems in contexts where re-identification is an obligation (medical records, legal proceedings). Choose your architecture knowingly, not by default.


Safe-doc: real-time pseudonymization, without storage, GDPR compliant

Setting up a GDPR-compliant document pseudonymization API takes time: architecture choice, key management, DPO documentation, load testing. Safe-doc compresses this timeline by offering a ready-to-use REST API, in stateless mode by default, with automatic detection of more than 90 types of PII on PDF, DOCX, XLSX and TXT.

Safe-doc

No documents are stored server-side. The encrypted mapping is exportable for your audit needs, and an auditability PDF report is generated for each processing. For teams using external LLMs (ChatGPT, Claude), Safe-doc integrates as an upstream pseudonymization layer, which neutralizes Shadow AI risk without changing work habits. The architecture details and security guarantees are publicly documented.

For DPOs and IT managers who need complete traceability, the page dedicated to compliance and audit details auditability features and deployment options. Request API access or a demonstration directly from this page.


Sources

This article constitutes general information and does not replace the advice of a qualified attorney. Consult a qualified legal professional regarding your individual case before acting on the basis of this content.

Recommendation