> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ferrum.thalamiq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Patch Resource

> Partially update a FHIR resource using JSON Patch

Applies partial modifications to a resource without replacing it entirely. Unlike PUT, only the specified fields are changed.

## Endpoint

```
PATCH /fhir/{resourceType}/{id}
```

<ParamField path="resourceType" type="string" required>
  The FHIR resource type (e.g., `Patient`, `Observation`, `Encounter`)
</ParamField>

<ParamField path="id" type="string" required>
  The logical ID of the resource to patch
</ParamField>

## Headers

<ParamField header="Content-Type" type="string" required>
  Patch format:

  * `application/json-patch+json` - JSON Patch (RFC 6902)
  * `application/fhir+json` - FHIRPath Patch (Parameters resource)
</ParamField>

<ParamField header="Accept" type="string">
  Response format: `application/fhir+json` (default) or `application/fhir+xml`
</ParamField>

<ParamField header="If-Match" type="string">
  Conditional patch. Only patch if current version matches this ETag.

  Example: `W/"5"`
</ParamField>

<ParamField header="Prefer" type="string">
  Response style:

  * `return=representation` (default) - Return full patched resource
  * `return=minimal` - Return headers only
  * `return=OperationOutcome` - Return OperationOutcome
</ParamField>

## Query Parameters

<ParamField query="search parameters" type="string">
  For conditional patch. Patch the resource matching these search parameters.

  Example: `?identifier=http://hospital.example/mrn|12345`
</ParamField>

## Request Body

### JSON Patch Format (Recommended)

Array of patch operations following RFC 6902:

<CodeGroup>
  ```json Replace Field theme={null}
  [
    {
      "op": "replace",
      "path": "/name/0/given/0",
      "value": "Jane"
    }
  ]
  ```

  ```json Add Field theme={null}
  [
    {
      "op": "add",
      "path": "/telecom/0",
      "value": {
        "system": "email",
        "value": "jane@example.com"
      }
    }
  ]
  ```

  ```json Remove Field theme={null}
  [
    {
      "op": "remove",
      "path": "/address/0"
    }
  ]
  ```

  ```json Multiple Operations theme={null}
  [
    {
      "op": "replace",
      "path": "/name/0/given/0",
      "value": "Jane"
    },
    {
      "op": "add",
      "path": "/active",
      "value": true
    },
    {
      "op": "remove",
      "path": "/photo"
    }
  ]
  ```
</CodeGroup>

**Supported Operations**:

* `add` - Add a value (creates if missing, appends to arrays)
* `remove` - Remove a value
* `replace` - Replace a value (must exist)
* `move` - Move a value from one path to another
* `copy` - Copy a value from one path to another
* `test` - Assert a value matches (fails patch if doesn't match)

### FHIRPath Patch Format

FHIR Parameters resource with FHIRPath expressions:

```json theme={null}
{
  "resourceType": "Parameters",
  "parameter": [
    {
      "name": "operation",
      "part": [
        {
          "name": "type",
          "valueCode": "replace"
        },
        {
          "name": "path",
          "valueString": "Patient.name[0].given[0]"
        },
        {
          "name": "value",
          "valueString": "Jane"
        }
      ]
    }
  ]
}
```

<Note>
  **Format Support**: Most servers support JSON Patch. FHIRPath Patch support varies. Check the server's CapabilityStatement.
</Note>

## Response

### 200 OK

Resource patched successfully.

<ResponseField name="meta.versionId" type="string" required>
  New version number (incremented)
</ResponseField>

<ResponseField name="meta.lastUpdated" type="string" required>
  ISO 8601 timestamp of this patch
</ResponseField>

<ResponseExample>
  ```json Patched Resource theme={null}
  {
    "resourceType": "Patient",
    "id": "123",
    "meta": {
      "versionId": "6",
      "lastUpdated": "2026-01-12T15:00:00.000Z"
    },
    "name": [
      {
        "family": "Doe",
        "given": ["Jane"]
      }
    ],
    "gender": "female",
    "birthDate": "1990-01-01",
    "active": true,
    "telecom": [
      {
        "system": "email",
        "value": "jane@example.com"
      }
    ]
  }
  ```

  Headers:

  ```
  HTTP/1.1 200 OK
  Content-Type: application/fhir+json
  ETag: W/"6"
  Last-Modified: Mon, 12 Jan 2026 15:00:00 GMT
  ```
</ResponseExample>

<Warning>
  **Narrative Removed**: Some servers (including Ferrum) remove the `text` (narrative) field after patching to prevent serving stale human-readable content.
</Warning>

### 400 Bad Request

Invalid patch operation or resulting resource invalid.

<ResponseExample>
  ```json Invalid Patch theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "invalid",
        "diagnostics": "Invalid patch operation: path '/invalid/path' not found in resource"
      }
    ]
  }
  ```
</ResponseExample>

### 404 Not Found

Resource doesn't exist.

<ResponseExample>
  ```json Not Found theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "not-found",
        "diagnostics": "Resource Patient/123 not found"
      }
    ]
  }
  ```
</ResponseExample>

### 412 Precondition Failed

Conditional patch failed (multiple matches or If-Match mismatch).

<ResponseExample>
  ```json Precondition Failed theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "multiple-matches",
        "diagnostics": "Multiple resources match search criteria. Conditional patch requires exactly one match."
      }
    ]
  }
  ```
</ResponseExample>

### 422 Unprocessable Entity

Patch applied but resulting resource violates validation rules.

<ResponseExample>
  ```json Validation Error theme={null}
  {
    "resourceType": "OperationOutcome",
    "issue": [
      {
        "severity": "error",
        "code": "business-rule",
        "expression": ["Patient.name"],
        "diagnostics": "Patient must have at least one name"
      }
    ]
  }
  ```
</ResponseExample>

## Examples

<CodeGroup>
  ```bash cURL - Basic Patch theme={null}
  curl -X PATCH "https://your-server.com/fhir/Patient/123" \
    -H "Content-Type: application/json-patch+json" \
    -H "Accept: application/fhir+json" \
    -d '[
      {
        "op": "replace",
        "path": "/name/0/given/0",
        "value": "Jane"
      }
    ]'
  ```

  ```bash cURL - Add Field theme={null}
  curl -X PATCH "https://your-server.com/fhir/Patient/123" \
    -H "Content-Type: application/json-patch+json" \
    -H "Accept: application/fhir+json" \
    -d '[
      {
        "op": "add",
        "path": "/telecom/0",
        "value": {
          "system": "email",
          "value": "jane@example.com"
        }
      },
      {
        "op": "add",
        "path": "/active",
        "value": true
      }
    ]'
  ```

  ```bash cURL - Remove Field theme={null}
  curl -X PATCH "https://your-server.com/fhir/Patient/123" \
    -H "Content-Type: application/json-patch+json" \
    -H "Accept: application/fhir+json" \
    -d '[
      {
        "op": "remove",
        "path": "/photo"
      }
    ]'
  ```

  ```bash cURL - Conditional Patch theme={null}
  curl -X PATCH "https://your-server.com/fhir/Patient?identifier=http://hospital.example/mrn|12345" \
    -H "Content-Type: application/json-patch+json" \
    -H "Accept: application/fhir+json" \
    -d '[
      {
        "op": "add",
        "path": "/active",
        "value": false
      }
    ]'
  ```

  ```python Python Example theme={null}
  import requests

  url = "https://your-server.com/fhir/Patient/123"
  headers = {
      "Content-Type": "application/json-patch+json",
      "Accept": "application/fhir+json"
  }
  patch = [
      {
          "op": "replace",
          "path": "/name/0/given/0",
          "value": "Jane"
      },
      {
          "op": "add",
          "path": "/active",
          "value": True
      }
  ]

  response = requests.patch(url, json=patch, headers=headers)
  if response.status_code == 200:
      patient = response.json()
      print(f"Patched to version {patient['meta']['versionId']}")
  ```

  ```javascript JavaScript Example theme={null}
  const url = 'https://your-server.com/fhir/Patient/123';

  const patch = [
    {
      op: 'replace',
      path: '/name/0/given/0',
      value: 'Jane'
    },
    {
      op: 'add',
      path: '/telecom/0',
      value: {
        system: 'email',
        value: 'jane@example.com'
      }
    }
  ];

  const response = await fetch(url, {
    method: 'PATCH',
    headers: {
      'Content-Type': 'application/json-patch+json',
      'Accept': 'application/fhir+json'
    },
    body: JSON.stringify(patch)
  });

  if (response.status === 200) {
    const patient = await response.json();
    console.log(`Patched to version ${patient.meta.versionId}`);
  }
  ```
</CodeGroup>

## JSON Patch Path Syntax

Paths use JSON Pointer notation (RFC 6901):

| Path              | Meaning                              |
| ----------------- | ------------------------------------ |
| `/name`           | Root-level `name` field              |
| `/name/0`         | First element of `name` array        |
| `/name/0/given`   | `given` field of first name          |
| `/name/0/given/0` | First given name                     |
| `/telecom/-`      | Append to `telecom` array (add only) |

<Tip>
  **Array Indexing**: Arrays are 0-indexed. Use `-` as the index to append to the end of an array (for `add` operation only).
</Tip>

## Best Practices

<Tip>
  **Prefer PATCH over PUT**: Use PATCH when you only need to change specific fields. It's more efficient and less error-prone than reading the full resource, modifying it, and PUTting it back.
</Tip>

<Warning>
  **Atomic Operations**: All operations in a patch are atomic. If any operation fails, the entire patch is rejected and no changes are made.
</Warning>

<Note>
  **Test Operation**: Use the `test` operation to verify a field has an expected value before applying changes. This provides additional safety:

  ```json theme={null}
  [
    { "op": "test", "path": "/active", "value": false },
    { "op": "replace", "path": "/active", "value": true }
  ]
  ```

  Fails if `active` is not currently `false`.
</Note>

## Common Use Cases

### Update Single Field

```json theme={null}
[{ "op": "replace", "path": "/active", "value": false }]
```

### Add Contact Information

```json theme={null}
[
  {
    "op": "add",
    "path": "/telecom/-",
    "value": {
      "system": "email",
      "value": "patient@example.com"
    }
  }
]
```

### Remove Sensitive Data

```json theme={null}
[
  { "op": "remove", "path": "/photo" },
  { "op": "remove", "path": "/contact/0/telecom" }
]
```

### Conditional Update with Safety

```json theme={null}
[
  { "op": "test", "path": "/status", "value": "draft" },
  { "op": "replace", "path": "/status", "value": "final" }
]
```

## See Also

<CardGroup cols={2}>
  <Card title="Update Resource" href="/api-reference/endpoint/update">
    Full resource replacement with PUT
  </Card>

  <Card title="Read Resource" href="/api-reference/endpoint/read">
    Get current version before patching
  </Card>

  <Card title="JSON Patch RFC" href="https://tools.ietf.org/html/rfc6902">
    Official JSON Patch specification
  </Card>

  <Card title="Learn FHIR CRUD" href="/learn-fhir/crud">
    Understand FHIR patch semantics
  </Card>
</CardGroup>


## OpenAPI

````yaml PATCH /{resourceType}/{id}
openapi: 3.1.0
info:
  title: Ferrum API
  description: >-
    FHIR R4 RESTful API implementation. All endpoints are prefixed with `/fhir`
    and follow the FHIR specification.
  version: 1.0.0
  contact:
    name: Ferrum
    url: https://github.com/thalamiq/ferrum
  license:
    name: MIT
servers:
  - url: http://localhost:8080/fhir
    description: Local development server (default port 8080)
  - url: https://your-server.com/fhir
    description: Production server (replace with your actual server URL)
  - url: https://api.example.com/fhir
    description: Example production server
security:
  - bearerAuth: []
paths:
  /{resourceType}/{id}:
    patch:
      tags:
        - CRUD
      summary: Patch Resource
      description: Partially update a resource using JSON Patch or FHIR Patch.
      operationId: patchResource
      parameters:
        - $ref: '#/components/parameters/ResourceType'
        - $ref: '#/components/parameters/Id'
      requestBody:
        required: true
        content:
          application/json-patch+json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/JsonPatchOperation'
          application/fhir+json:
            schema:
              $ref: '#/components/schemas/Parameters'
      responses:
        '200':
          description: Resource patched
          content:
            application/fhir+json:
              schema:
                $ref: '#/components/schemas/Resource'
        '400':
          $ref: '#/components/responses/BadRequest'
        '404':
          $ref: '#/components/responses/NotFound'
components:
  parameters:
    ResourceType:
      name: resourceType
      in: path
      required: true
      description: The FHIR resource type (e.g., Patient, Observation, Encounter)
      schema:
        type: string
    Id:
      name: id
      in: path
      required: true
      description: The logical ID of the resource
      schema:
        type: string
  schemas:
    JsonPatchOperation:
      type: object
      description: A JSON Patch operation (RFC 6902)
      required:
        - op
        - path
      properties:
        op:
          type: string
          enum:
            - add
            - remove
            - replace
            - move
            - copy
            - test
          description: The operation to perform
        path:
          type: string
          description: A JSON Pointer path
        value:
          description: The value to use
        from:
          type: string
          description: A JSON Pointer path (for move/copy operations)
    Parameters:
      type: object
      description: >-
        This resource is a non-persisted resource used to pass information into
        and back from an operation
      required:
        - resourceType
      properties:
        resourceType:
          type: string
          enum:
            - Parameters
        parameter:
          type: array
          items:
            $ref: '#/components/schemas/ParametersParameter'
    Resource:
      type: object
      description: A FHIR resource. All resources have resourceType, id, and meta fields.
      required:
        - resourceType
      properties:
        resourceType:
          type: string
          description: The type of resource
        id:
          type: string
          description: Logical id of this artifact
        meta:
          $ref: '#/components/schemas/Meta'
      additionalProperties: true
    ParametersParameter:
      type: object
      properties:
        name:
          type: string
        valueString:
          type: string
        valueBoolean:
          type: boolean
        valueInteger:
          type: integer
        valueDecimal:
          type: number
        valueUri:
          type: string
          format: uri
        valueDateTime:
          type: string
          format: date-time
        valueResource:
          $ref: '#/components/schemas/Resource'
        part:
          type: array
          items:
            $ref: '#/components/schemas/ParametersParameter'
    Meta:
      type: object
      description: Metadata about a resource
      properties:
        versionId:
          type: string
          description: Version specific identifier
        lastUpdated:
          type: string
          format: date-time
          description: When the resource version last changed
        profile:
          type: array
          items:
            type: string
            format: uri
          description: Profiles this resource claims to conform to
        tag:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
          description: Tags applied to this resource
        security:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
          description: Security labels applied to this resource
    OperationOutcome:
      type: object
      description: >-
        A collection of error, warning or information messages that result from
        a system action
      required:
        - resourceType
      properties:
        resourceType:
          type: string
          enum:
            - OperationOutcome
          description: Resource type
        issue:
          type: array
          items:
            $ref: '#/components/schemas/OperationOutcomeIssue'
          description: A list of issues associated with the operation
    Coding:
      type: object
      description: A reference to a code defined by a terminology system
      properties:
        system:
          type: string
          format: uri
          description: Identity of the terminology system
        version:
          type: string
          description: Version of the system - if relevant
        code:
          type: string
          description: Symbol in syntax defined by the system
        display:
          type: string
          description: Representation defined by the system
    OperationOutcomeIssue:
      type: object
      description: An issue associated with the operation
      required:
        - severity
        - code
      properties:
        severity:
          type: string
          enum:
            - fatal
            - error
            - warning
            - information
          description: Severity of the issue
        code:
          type: string
          enum:
            - invalid
            - structure
            - required
            - value
            - invariant
            - security
            - login
            - unknown
            - expired
            - forbidden
            - suppressed
            - processing
            - not-supported
            - duplicate
            - multiple-matches
            - not-found
            - deleted
            - too-long
            - code-invalid
            - extension
            - too-costly
            - business-rule
            - conflict
            - transient
            - lock-error
            - no-store
            - exception
            - timeout
            - incomplete
            - throttled
            - informational
          description: Error or warning code
        details:
          $ref: '#/components/schemas/CodeableConcept'
        diagnostics:
          type: string
          description: Additional diagnostic information about the issue
        location:
          type: array
          items:
            type: string
          description: XPath or JSONPath expression describing the location of the issue
    CodeableConcept:
      type: object
      description: >-
        A concept that may be defined by a formal reference to a terminology or
        ontology
      properties:
        coding:
          type: array
          items:
            $ref: '#/components/schemas/Coding'
        text:
          type: string
          description: Plain text representation of the concept
  responses:
    BadRequest:
      description: Bad request - validation error or invalid input
      content:
        application/fhir+json:
          schema:
            $ref: '#/components/schemas/OperationOutcome'
    NotFound:
      description: Resource not found
      content:
        application/fhir+json:
          schema:
            $ref: '#/components/schemas/OperationOutcome'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: Bearer token authentication

````