Blog

Document pseudonymization API: guide for developers and CISOs

Stylish cover illustration for Pseudonymization API user guide

To pseudonymize documents via an API in France, the minimum viable configuration is based 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 in compliance 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 technical recommendation from the CNIL on secure data sharing via API, the open-source repository Court-of-cassation/pseudonymisation-api, the product documentation Teavaro, and the French SaaS solution Safe-doc.

  • Check that your endpoints expose at least `/pseudonymise` and `/ner`.
  • Enable TLS on all calls, without exception.
  • Define a separate 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 allows you to join datasets without ever exposing the plain identifier.


Key points

PointDetails
Domain separationA separate domain per application prevents database overlap between partners.
Choice of architectureStateless if no re-identification; stateful with AES-256-GCM encrypted mapping if necessary.
CNIL checklistDocument transformations, separate bases, check robustness against reidentification.
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 which means you don't have to rediscover the wheel with each integration.

Common endpoints

EndpointMethodRole
`/pseudonymise`POSTReplaces detected PII with pseudonyms (UUID, token, FPE value)
`/ner`POSTNamed entity detection; 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 (health)
`/fhir/$de-pseudonymize`POSTControlled reidentification of FHIR resources

API access point diagram showing the methods used and associated user profiles

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

Essential parameters to document

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

HTTP codes and error handling

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

Separation by domain 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 reidentification.


How to pseudonymize a document via API, step by step

The entire pipeline follows seven sequential steps. Here's how to chain them together in production.

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

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

```bash

curl -X POST __PH28__ \

-H "Authorization: Bearer $TOKEN" \

-F "file=@contrat.pdf" \

-F "domain=juridique-client-a"

```

3. Déclencher l'extraction OCR si nécessaire. Pour les PDF scannés, l'API lance une étape OCR avant la détection NER. Certains services l'intègrent automatiquement ; d'autres exposent un endpoint `/ocr` séparé.

4. Lancer la détection NER et les règles métier. L'API identifie les entités (noms, SIREN, IBAN, adresses, dates) via un modèle NER et des règles configurables. Le projet enki-run/shield combine spaCy et Presidio avec des règles personnalisables, tout en conservant les en-têtes de colonnes CSV/XLSX intacts.

5. Générer les pseudonymes. Selon la configuration, la valeur de remplacement est un UUID aléatoire, un token HMAC déterministe, ou une valeur FPE conforme au RFC 5297 qui préserve le format original (utile pour les numéros de téléphone ou les codes postaux).

6. Récupérer le document pseudonymisé et le mapping. L'API retourne le document traité et, si le mode stateful est activé, un mapping chiffré `{ pseudonym: original_value }` à conserver de votre côté.

```bash

curl -X POST __PH29__ \

-H "Authorization: Bearer $TOKEN" \

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

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

```

7. Journaliser et exporter le mapping. Enregistrez l'identifiant de traitement, l'horodatage, le domaine et le hash du document original. Exportez le mapping chiffré dans un coffre séparé de la base de production.

Formats supportés et limites techniques

  • PDF (natif et scanné avec OCR), DOCX, XLSX, CSV, TXT sont les formats les plus répandus.
  • Les fichiers XLSX et CSV : les en-têtes de colonnes ne doivent jamais être pseudonymisés.
  • Limite d'encodage : UTF-8 obligatoire pour les fichiers texte ; les encodages legacy (ISO-8859-1) doivent être convertis en amont.

Conseil de pro : Conservez toujours les en-têtes de colonnes CSV/XLSX inchangés. Pseudonymiser les noms de colonnes casse la compatibilité de tous vos pipelines avals, des requêtes SQL aux imports BI. Traitez uniquement les valeurs de cellule.


Authentification, sécurité et choix d'architecture : stateless ou stateful ?

Le choix entre stateless et stateful conditionne à la fois votre posture RGPD et votre surface d'attaque.

Stateless vs stateful : les implications concrètes

En mode stateless, l'API ne conserve aucun mapping après le traitement. Le document pseudonymisé est retourné immédiatement, sans persistance côté serveur. La réidentification devient impossible sans que le client ne conserve lui-même le mapping. C'est l'architecture recommandée pour les traitements LLM externes et les cas où la réidentification n'est jamais nécessaire.

La réidentification reste possible via une procédure contrôlée, journalisée et à accès restreint. Le __PH17__ décrit une méthode avancée basée sur ECC et aveuglement (blinding) : ni le client ni le service central ne peuvent seuls reconstruire l'identifiant clair sans procédure conjointe.

CritèreStatelessStateful
Stockage du mappingAucun côté serveurPersisté (chiffré)
RéidentificationImpossible sans mapping clientPossible via procédure contrôlée
Cas d'usage recommandéLLM externes, analyses sans retourDossiers médicaux, juridique avec archivage
Risque principalPerte définitive si mapping client perduFuite du mapping = réidentification
Conformité RGPDSimplifiée (pas de base de mapping)Exige DPA, accès restreint, journalisation

Options d'authentification

  • Clé API (`X-API-Key`) : simple à implémenter, suffisant pour des environnements internes contrôlés.
  • OAuth 2.0 (client credentials) : recommandé pour les intégrations machine-to-machine en production.
  • mTLS : authentification mutuelle par certificat, pour les environnements à haute exigence de sécurité.

Quelle que soit l'option choisie, implémentez une rotation régulière des clés et stockez-les dans un coffre à secrets (HashiCorp Vault, AWS Secrets Manager ou équivalent). Les tokens d'accès doivent avoir une durée de vie courte, surtout pour les traitements impliquant des LLM externes.

Mesures complémentaires obligatoires

  • TLS 1.2 minimum sur tous les endpoints, avec HSTS activé.
  • Chiffrement au repos des mappings en AES-256-GCM (comme le fait enki-run/shield).
  • Journalisation d'accès immuable : qui a accédé à quel domaine, quand, avec quel résultat.
  • Séparation des environnements : ne jamais utiliser des clés de production en développement.

Conseil de pro : Pour les traitements via LLM externes (ChatGPT, Claude), n'accordez que des tokens à courte durée de vie (15-30 minutes maximum) et limitez leur périmètre au seul domaine concerné. Un token compromis ne doit jamais donner accès à l'ensemble des domaines de pseudonymisation.


Checklist CNIL et RGPD pour l'usage d'une API de pseudonymisation en France

La recommandation technique de la CNIL sur le partage sécurisé de données via API pose des exigences précises que tout déploiement en France doit respecter.

Points obligatoires

  • Documenter les transformations appliquées : algorithme, domaine, version du modèle NER, date de mise à jour des règles.
  • Séparer physiquement ou logiquement la base source des données brutes de la base des pseudonymes.
  • Vérifier la robustesse du procédé face aux méthodes de réidentification connues (attaques par recoupement, inférence, singling-out).
  • Définir une politique de conservation minimale : ne conserver les mappings que le temps strictement nécessaire.

Points fortement recommandés

  • Fournir aux réutilisateurs une documentation décrivant la fréquence de mise à jour, la granularité des données, les formats, la profondeur historique et les mesures de pseudonymisation appliquées.
  • Mettre en place un export des journaux d'audit au format PDF ou structuré, consultable par le DPO.
  • Définir une politique de réversibilité explicite : qui peut demander la réidentification, dans quel délai, avec quelle traçabilité.
  • Restreindre l'accès aux clés de déchiffrement et journaliser chaque utilisation.

La pseudonymisation selon l'article 4(5) du RGPD ne dispense pas du respect des principes de minimisation et de limitation de la conservation. Elle réduit le risque résiduel, mais les données pseudonymisées restent des données à caractère personnel tant que le mapping existe. La recommandation CNIL rappelle que la séparation des bases est la mesure organisationnelle la plus efficace pour limiter ce risque.

Les guides Etalab sur la pseudonymisation complètent ce cadre avec des bonnes pratiques françaises pour la gouvernance des données partagées, notamment sur la documentation des méthodes et la traçabilité des transformations.

Pour les équipes qui gèrent des documents sensibles au sens de l'article 4(5) du RGPD, la page pseudonymisation RGPD de Safe-doc détaille les distinctions légales entre anonymisation et pseudonymisation et leurs implications pratiques pour la documentation.


__PH2__

Exemples d'intégration et tests : curl, JavaScript et Python

Snippets prêts à l'emploi

curl

```bash

Pseudonymisation d'un document texte

curl -X POST __PH30__ \

-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"

}'

Réponse attendue :

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

```

JavaScript (fetch)

```javascript

const response = await fetch('__PH31__ {

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(

'__PH32__

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: check that the CSV/XLSX column names are identical before and after processing.

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

3. Assertion on the encrypted mapping: check that the returned mapping is 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 only anonymized fixtures (never real production data) and simulate separate domains for each test environment. A test that goes into production with real PII data is a potential GDPR violation, even in a testing context.

Checklist before production

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

Best practices and common errors to avoid in production

Best practices

  • Assign a separate domain per application, per partner and per environment (dev/staging/prod).
  • Enable immutable logging: each call should trace the request ID, domain, timestamp and result.
  • Systematically encrypt mappings at rest in AES-256-GCM.
  • Minimize data sent to the API: only send necessary fields, not the entire document if only a section contains PII.
  • Review NER rules and detection patterns regularly, at least every time the underlying language model is updated.

Common errors

  • Pseudonymize file headers: breaks all downstream pipelines that rely on column names.
  • Forget domain separation: two applications sharing the same domain can overlap their pseudonym bases.
  • Store mappings without encryption: a clear mapping is a basis for direct re-identification.
  • Use long-lived tokens for external LLMs: Shadow AI thrives on precisely this type of uncontrolled access.
  • Do not test error handling: an API that returns 500 without the client handling it can silently let non-pseudonymized PII through.

The separation of domains 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 access to mapping, 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-kept README is better than a report written after the fact under pressure.


Technical and audit checklist before production

Technical checks

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

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

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

4. Saving encrypted mappings in a safe 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 conservation rules defined and implemented.
  • Documented, logged and restricted access temporary re-identification procedure.

Tests required before opening

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

Operations

  • Documented rollback plan in case of API failure.
  • API SLA checked and uptime alerts configured.
  • Monitoring of main endpoints with alert thresholds on latency and error rate.
  • Escalation procedure in the event of a confidentiality incident.

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

Most articles on API pseudonymization stop at the list of endpoints and a snippet curl. This is insufficient for 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 an intersection graph that any analyst can leverage. Domain separation is the most underrated metric in all of architecture.

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

Finally, stateless mode is often presented as “simpler”. It technically is, but it shifts responsibility for mapping 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 wisely, not by default.


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

Setting up a GDPR-compliant document pseudonymization API takes time: choice of architecture, key management, documentation for the DPO, load testing. Safe-doc compresses this time 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 auditing needs, and an auditability PDF report is generated for each processing. For teams using external LLMs (ChatGPT, Claude), Safe-doc is integrated as an upstream pseudonymization layer, which neutralizes Shadow AI risk without changing work habits. architectural details and security guarantees are publicly documented.

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


Sources

This article constitutes general information and is not a substitute for advice from a qualified attorney. Consult a qualified legal professional regarding your individual case before acting on this content.

Recommendation