---
title: "Redacting PHI in FHIR Resources"
description: "Redact PHI in FHIR resources and bulk exports with Philter: remove structured Patient elements by rule, pseudonymize IDs and references, and send free text to Philter. A verified Python example."
url: "https://philterd.ai/guides/redacting-phi-in-fhir-resources/"
---

[Knowledge base](https://philterd.ai/guides/) [How-to](https://philterd.ai/guides/?kind=how-to)

# Redacting PHI in FHIR Resources

Redact PHI in FHIR resources and bulk exports with Philter: remove structured Patient elements by rule, pseudonymize IDs and references, and send free text to Philter. A verified Python example.

For [Philter](https://philterd.ai/support/philter/)

This guide shows how to redact protected health information (PHI) in FHIR resources with [Philter](https://philterd.ai/philter/), one resource at a time or in a bulk export. Philter does not read FHIR directly, so a small script walks each resource and handles each element by what it holds:

- **Structured Patient elements**, such as `name`, `telecom`, `address`, and `contact`, are removed by rule, with no detection, and `birthDate` is cut to the year.
- **IDs that link resources**, such as the Patient’s `id`, its `identifier` values, and every `Patient/...` reference, get a keyed pseudonym, so resources for one patient still link after redaction.
- **Free-text elements**, such as `valueString`, annotation `text`, and `conclusion`, go to Philter, which finds names, phone numbers, email addresses, dates, and other identifiers inside the text.
- **The narrative** (`text.div`) repeats the structured data as XHTML, so the script drops it rather than scanning it.

Everything runs in your own environment: Philter is open source and self-hosted, and no resource leaves your network.

Redaction is probabilistic. Detection in free text reduces how much PHI gets through, but it does not catch every instance, so validate the output against your own data before you rely on it.

![A FHIR resource is redacted element by element. Structured Patient elements such as name, telecom, address, and contact are removed by rule. The Patient id, identifier values, and Patient references get a keyed pseudonym so resources still link. Free-text elements such as valueString and notes go to Philter. The XHTML narrative is dropped.](https://philterd.ai/images/guides/guide-fhir-element-treatments.svg)

## Start Philter and load a policy

Start Philter and wait until it is healthy:

```bash
export PHILTER_ENCRYPTION_KEY="$(openssl rand -base64 32)"
export PHILTER_API_KEY="sk_$(openssl rand -hex 16)"

docker run -d --name philter -p 8080:8080 \
  -e PHILTER_ENCRYPTION_KEY \
  -e PHILTER_BOOTSTRAP_API_KEY="$PHILTER_API_KEY" \
  -v philter-data:/opt/philter/data \
  philterd/philter:4.0.1

until curl -skf https://localhost:8080/api/health > /dev/null; do sleep 2; done
```

Philter’s built-in `default` policy finds only person names, SSNs, and email addresses. Load the [HIPAA Safe Harbor policy](https://philterd.ai/policies/healthcare/hipaa-safe-harbor/) from the policy library instead, which also covers phone numbers, dates, addresses, and the other Safe Harbor identifiers:

```bash
curl -sfLO https://raw.githubusercontent.com/philterd/pii-redaction-policies/main/policies/philterd/healthcare/hipaa-safe-harbor.json

curl -sk -X POST "https://localhost:8080/api/policies?name=hipaa-safe-harbor" \
  -H "Authorization: Bearer $PHILTER_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @hipaa-safe-harbor.json
```

## The script

`redact_fhir.py` uses only the Python standard library. It reads a single resource or Bundle as JSON, or a bulk export file as NDJSON (one resource per line, when the file name ends in `.ndjson`).

```python
import hashlib
import hmac
import json
import os
import ssl
import sys
import urllib.request

PHILTER_URL = os.environ.get("PHILTER_URL", "https://localhost:8080")
PHILTER_API_KEY = os.environ["PHILTER_API_KEY"]
PSEUDONYM_KEY = os.environ["PSEUDONYM_KEY"].encode()
POLICY = os.environ.get("PHILTER_POLICY", "default")

# Philter's default certificate is self-signed. Use your own certificate in production.
TLS = ssl.create_default_context()
TLS.check_hostname = False
TLS.verify_mode = ssl.CERT_NONE

# Patient elements removed without detection.
PATIENT_REMOVE = ["name", "telecom", "address", "contact", "photo"]

# Elements whose string value is free text, sent to Philter for detection.
TEXT_KEYS = {"valueString", "text", "conclusion", "description", "comment"}


def philter(text):
    request = urllib.request.Request(
        f"{PHILTER_URL}/api/filter?p={POLICY}",
        data=text.encode("utf-8"),
        headers={"Authorization": f"Bearer {PHILTER_API_KEY}", "Content-Type": "text/plain"},
    )
    with urllib.request.urlopen(request, context=TLS) as response:
        return response.read().decode("utf-8")


def pseudonym(value):
    # The same value always gets the same stand-in, so resources for one patient still link.
    return hmac.new(PSEUDONYM_KEY, value.encode("utf-8"), hashlib.sha256).hexdigest()[:16]


def redact_patient(patient):
    for key in PATIENT_REMOVE:
        patient.pop(key, None)
    if "birthDate" in patient:
        patient["birthDate"] = patient["birthDate"][:4]
    for identifier in patient.get("identifier", []):
        if "value" in identifier:
            identifier["value"] = pseudonym(identifier["value"])


def walk(node):
    if isinstance(node, list):
        return [walk(item) for item in node]
    if not isinstance(node, dict):
        return node
    if node.get("resourceType") == "Patient":
        redact_patient(node)
        if "id" in node:
            node["id"] = pseudonym(node["id"])
    # The narrative repeats the structured data as XHTML, so drop it rather than scan it.
    if isinstance(node.get("text"), dict) and "div" in node["text"]:
        del node["text"]
    node.pop("authorString", None)
    for key, value in node.items():
        if key == "reference" and isinstance(value, str) and value.startswith("Patient/"):
            node[key] = "Patient/" + pseudonym(value[len("Patient/"):])
        elif key == "fullUrl" and isinstance(value, str) and "Patient/" in value:
            base, _, patient_id = value.rpartition("Patient/")
            node[key] = base + "Patient/" + pseudonym(patient_id)
        elif key in TEXT_KEYS and isinstance(value, str):
            node[key] = philter(value)
        else:
            node[key] = walk(value)
    return node


if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        if sys.argv[1].endswith(".ndjson"):
            for line in f:
                if line.strip():
                    print(json.dumps(walk(json.loads(line))))
        else:
            print(json.dumps(walk(json.load(f)), indent=2))
```

## Run it

Given `bundle.json`, a Bundle with a Patient and an Observation holding invented data:

```json
{
  "resourceType": "Bundle",
  "type": "collection",
  "entry": [
    {
      "fullUrl": "https://fhir.example.org/Patient/pat-1001",
      "resource": {
        "resourceType": "Patient",
        "id": "pat-1001",
        "text": {
          "status": "generated",
          "div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">Jane Doe, born 1980-02-14</div>"
        },
        "identifier": [
          { "system": "https://fhir.example.org/mrn", "value": "MRN12345" }
        ],
        "name": [ { "family": "Doe", "given": [ "Jane" ] } ],
        "telecom": [ { "system": "phone", "value": "(217) 555-0142" } ],
        "gender": "female",
        "birthDate": "1980-02-14",
        "address": [ { "line": [ "123 Main St" ], "city": "Springfield", "state": "IL", "postalCode": "62701" } ],
        "contact": [ { "name": { "family": "Doe", "given": [ "John" ] }, "telecom": [ { "system": "phone", "value": "(217) 555-0199" } ] } ]
      }
    },
    {
      "fullUrl": "https://fhir.example.org/Observation/obs-2001",
      "resource": {
        "resourceType": "Observation",
        "id": "obs-2001",
        "status": "final",
        "code": { "text": "Clinical note" },
        "subject": { "reference": "Patient/pat-1001" },
        "valueString": "Patient Jane Doe reports fatigue. Her husband John Doe can be reached at (217) 555-0199 or john.doe@example.com.",
        "note": [
          { "authorString": "Dr. Alan Smith", "text": "Discussed results with Dr. Alan Smith on 11/30/2026." }
        ]
      }
    }
  ]
}
```

Run the script with the Safe Harbor policy and a secret key for the pseudonyms:

```bash
export PSEUDONYM_KEY="example-secret-change-me"
PHILTER_POLICY=hipaa-safe-harbor python3 redact_fhir.py bundle.json
```

The first request loads the person-name model and takes a few seconds. Later requests are fast.

Output:

```json
{
  "resourceType": "Bundle",
  "type": "collection",
  "entry": [
    {
      "fullUrl": "https://fhir.example.org/Patient/1bf615292d7f6e35",
      "resource": {
        "resourceType": "Patient",
        "id": "1bf615292d7f6e35",
        "identifier": [
          {
            "system": "https://fhir.example.org/mrn",
            "value": "131f18ea8c5e15b1"
          }
        ],
        "gender": "female",
        "birthDate": "1980"
      }
    },
    {
      "fullUrl": "https://fhir.example.org/Observation/obs-2001",
      "resource": {
        "resourceType": "Observation",
        "id": "obs-2001",
        "status": "final",
        "code": {
          "text": "Clinical note"
        },
        "subject": {
          "reference": "Patient/1bf615292d7f6e35"
        },
        "valueString": "Patient {{{REDACTED-name}}} reports fatigue. Her husband {{{REDACTED-name}}} can be reached at {{{REDACTED-phone-number}}} or {{{REDACTED-email-address}}}.",
        "note": [
          {
            "text": "Discussed results with Dr. {{{REDACTED-name}}} on {{{REDACTED-date}}}."
          }
        ]
      }
    }
  ]
}
```

The Observation’s `subject` still points at the Patient, through the same pseudonym as the Patient’s `id` and `fullUrl`. The MRN pseudonym, `131f18ea8c5e15b1`, is the one the [HL7 guide](https://philterd.ai/guides/redacting-phi-in-hl7-v2-messages/) produces for the same MRN and key, so redacted FHIR data and redacted HL7 messages can still be joined on the patient. Keep `PSEUDONYM_KEY` secret: anyone who holds it can test a guessed identifier against the pseudonyms.

For a bulk export, pass the NDJSON file instead. The output has one redacted resource per line:

```bash
PHILTER_POLICY=hipaa-safe-harbor python3 redact_fhir.py Patient.ndjson
```

## Adapting it to your data

- **Add rules for the resource types you export.** The script removes structured elements from Patient only. Practitioner, RelatedPerson, and Person carry names, phone numbers, and addresses too, and Encounter and other resources carry dates that Safe Harbor covers, such as admission and discharge dates. Add each as a rule.
- **Check references to other resource types.** The script pseudonymizes `Patient/...` references only. If you also replace the IDs of other resources, rewrite their references the same way, and include `Bundle.entry.fullUrl`.
- **Check extensions.** Extensions your organization defines can hold PHI in structured values that the script neither removes nor scans. Add rules for them.
- **Rebuild the narrative if a consumer needs it.** Dropping `text` keeps the resource valid. If a receiving system expects a narrative, generate a new one from the redacted resource.
- **Plan for volume.** The script makes one request per free-text value. For a large bulk export, split the NDJSON files across several Philter instances.

## Safe Harbor is more than redaction

HIPAA’s Safe Harbor method requires removing all 18 identifier types and having no actual knowledge that what remains could identify someone. Rules and detection help with the first part. The second is a judgment about your data that your privacy officer makes, so review a sample of redacted resources before you treat an export as de-identified.

## Native FHIR support

Philter takes FHIR content through this kind of script today. Path rules for JSON documents such as FHIR resources, written in the redaction policy itself, are proposed in [philterd/phisql#98](https://github.com/philterd/phisql/issues/98). Comment there if your organization would use them.
