Skip to content

F12.14 — JSON Merge Patch

State Closed
Parent E12
Iteration Release 3
Start Date 2026-10-04
Closed Date 2026-10-04
Predecessors —
Source Owner request, 2026-09-28

Stories: 6 Closed

Story State Depends on
S12.14.1 — Check for a maintained library Closed (2026-10-04) —
S12.14.2 — The framework-neutral merge in rn-forge-web Closed (2026-10-04) —
S12.14.3 — Conformance cases Closed (2026-10-04) —
S12.14.4 — Django binding Closed (2026-10-04) —
S12.14.5 — FastAPI binding Closed (2026-10-04) —
S12.14.6 — Documentation and release notes Closed (2026-10-04) —

The API conventions already say PATCH is RFC 7396 JSON Merge Patch, but no package implements it. rn-forge-django's only JSON parser accepts application/json, so DRF answers a merge-patch request with 415, and DRF's partial update does not treat null as "remove this field": it validates the null against the serializer field. rn-forge-fastapi has no PATCH helper at all, and a pydantic.ValidationError raised inside a route is not mapped to a 422: it reaches the catch-all handler as a 500. Every application therefore writes its own merge, and each gets null, nested objects or arrays slightly differently.

RFC 7396 in one paragraph: the body is a partial copy of the resource. A member that is present sets the field, an absent member leaves it alone, a null member removes it, objects merge recursively and arrays are replaced whole.

Context

Outcome: a browser client's resource screen fired the trigger; the client's work did not gate this feature (ADR-0008). It changed BaseModelViewSet's PATCH media type, a breaking change.

Design

Outcome: one framework-neutral merge in rn_forge.web.merge_patch (ADR-0005), which each adapter only binds, shipped on 2026-10-04; the API conventions §10 Merge patch own the wire rules, and the merge-patch reference lists the shared symbols. The merge is hand-rolled under ADR-0001 rule 1's third condition: the S12.14.1 search found only json-merge-patch 0.3.0, untyped, in-place and not clearly maintained, and no other RFC 7396 implementation.

Request order

Outcome: the API conventions' Merge patch section states the order: media type, precondition, body shape, then validation.

null on a declared field

Outcome: the API conventions state the top-level null rule. It exists because DRF's full update skips a missing optional field instead of clearing it, so a null that only removed the member would leave the stored value unchanged.

The conformance fixture

Outcome: each driver serves /conformance/documents/1; the patch area's cases are in CASES, documented in the conformance reference. All three packages took a minor version with no deprecation window, rn-forge-web tagged first, and F12.12's removals shipped in the same rn-forge-django version.

S12.14.1 — Check for a maintained library

State: Closed (2026-10-04)

Acceptance: PyPI is searched for a maintained RFC 7396 implementation, per ADR-0001 rule 1, and the result is recorded under Design: either the package is adopted, with the owner's approval of the new dependency, or the reason to hand-roll is named. If one is adopted, S12.14.2's apply_merge_patch wraps it and the module docstring says so.

S12.14.2 — The framework-neutral merge in rn-forge-web

State: Closed (2026-10-04)

Acceptance:

  • A new module rn_forge.web.merge_patch defines, and rn_forge.web re-exports:
    • MERGE_PATCH_MEDIA_TYPE = "application/merge-patch+json";
    • apply_merge_patch(target, patch), which follows RFC 7396 §2 exactly and mutates neither argument;
    • merge_representation(current, patch), which applies the top-level null rule and then apply_merge_patch below the top level;
    • require_patch_object(body), which returns body when it is a JSON object and raises InvalidMergePatch otherwise.
  • rn_forge.web.problem gains UNSUPPORTED_MEDIA_TYPE = ProblemType("unsupported-media-type", 415, "Unsupported Media Type") and NULL_FIELD_DETAIL = "This field may not be null." (DRF's own wording, so both stacks already agree on it). Both are re-exported beside CONTENT_TOO_LARGE and REQUIRED_FIELD_DETAIL.
  • rn_forge.web.exceptions gains two WebError subclasses, both registered in default_registry():
    • UnsupportedMediaType maps to 415. Like TooManyRequests, it carries a response_headers() result, here Accept-Patch: application/merge-patch+json (RFC 5789 §2.2). Its detail is Use Content-Type: application/merge-patch+json for PATCH.
    • InvalidMergePatch maps to 422 with detail A merge patch must be a JSON object., and has no errors member.
  • tests/test_merge_patch.py runs every example in RFC 7396 Appendix A through apply_merge_patch. It also covers: nested merge; null removing a member that is absent (a no-op); array replacement; a scalar or list patch replacing the target (RFC §2); no mutation of either argument; merge_representation keeping a top-level null and still removing a nested one; and require_patch_object rejecting a list, a string and null.
  • The module imports no web framework, and uv run pyright and uv run lint-imports pass.

S12.14.3 — Conformance cases

State: Closed (2026-10-04)

Acceptance: ConformanceArea gains "patch", and rn_forge.web.conformance.CASES gains the cases in The conformance fixture, with ids beginning patch.. Both framework drivers serve /conformance/documents/1 and run every case with no skips. Each driver's issue() sends the case's own Content-Type for a JSON body, rather than forcing application/json.

S12.14.4 — Django binding

State: Closed (2026-10-04)

Acceptance:

  • rn_forge.django.drf.casing gains MergePatchParser, a CamelCaseJSONParser subclass whose media_type is MERGE_PATCH_MEDIA_TYPE. rn_forge.django.drf gains MergePatchMixin (in views/mixins.py), and both are re-exported from rn_forge.django.drf.
  • MergePatchMixin.get_parsers() returns [MergePatchParser()] for PATCH only. For PUT and POST it keeps the view's other parsers and never includes the merge-patch parser.
  • MergePatchMixin.partial_update runs in this order:
    1. It checks the media type before reading request.data. Any PATCH whose media type, ignoring parameters, is not MERGE_PATCH_MEDIA_TYPE raises rn_forge.web.UnsupportedMediaType.
    2. It calls get_object().
    3. When the instance is a VersionedModelMixin, it calls enforce_version(request, instance, required=self.merge_patch_requires_if_match, codec=self.etag_codec). Both class attributes default to False and None.
    4. It calls require_patch_object(request.data).
    5. It calls merge_representation(serializer.data, patch), where serializer.data is the current instance serialized.
    6. It validates the merged document with get_serializer(instance, data=merged), a full update rather than partial=True, and saves it through perform_update.
    7. It answers 200 with the new representation, plus ETag from etag_for when the instance is versioned.
  • MergePatchMixin.retrieve adds the same ETag header for a versioned instance. That makes the read-then-If-Match round trip work without view code.
  • BaseModelViewSet includes MergePatchMixin.
  • The generated OpenAPI document lists application/merge-patch+json, and only that, as the PATCH request body's content type for a BaseModelViewSet.
  • tests/drf/test_merge_patch.py covers: each step's failure (415, 428 when required, 412, a non-object 422, a null on a non-nullable field 422); PUT refusing the merge-patch media type; the ETag on retrieve and PATCH; the audit fields still set by perform_update; and the OpenAPI content type. tests/test_conformance.py passes with the new cases.

S12.14.5 — FastAPI binding

State: Closed (2026-10-04)

Acceptance:

  • A new module rn_forge.fastapi.merge_patch holds three functions, all re-exported from rn_forge.fastapi:
    • merge_patch_body() returns a dependency. The dependency raises UnsupportedMediaType unless the request's media type, ignoring parameters, is MERGE_PATCH_MEDIA_TYPE, and returns the raw body bytes unparsed.
    • merge_into(model, current, body) parses body as JSON and passes it through require_patch_object, so unparseable JSON and a non-object both raise InvalidMergePatch. It then dumps current through model (model_validate(current, from_attributes=True).model_dump(by_alias=True, mode="json")), applies merge_representation, and validates the result with model. On a pydantic.ValidationError it raises fastapi.exceptions.RequestValidationError with each loc prefixed by "body", so the existing handler renders a 422 with RFC 6901 pointers. It never lets a ValidationError reach the catch-all handler.
    • merge_patch_openapi() returns the openapi_extra mapping that declares the request body as application/merge-patch+json with schema {"type": "object"}.
  • rn_forge.fastapi.problem._validation_errors maps an entry whose input is None and whose type is not missing to NULL_FIELD_DETAIL, as it already maps missing to REQUIRED_FIELD_DETAIL.
  • The route order is the same as Django's and follows the request order: merge_patch_body is declared before require_if_match, so the media type answers first; the route checks the stale version with check_precondition; and only then does merge_into parse the body, check it is an object, merge and validate. FastAPI resolves dependencies in declaration order, so the object check cannot live in the dependency without answering before the precondition. The tests pin 415 before 428, 400 before a non-object 422, and 412 before a non-object 422.
  • tests/test_merge_patch.py covers each function and the ordering, and tests/test_conformance.py passes with the new cases.

S12.14.6 — Documentation and release notes

State: Closed (2026-10-04)

Acceptance:

  • The API conventions' §10 describes the semantics in Design: the request order, the top-level null rule, ignored read-only members, 415 with Accept-Patch, and the conformance case ids. A new rn-forge-web reference page documents rn_forge.web.merge_patch. Each adapter's wiring guide shows its binding, and each adapter's reference pages list the new symbols.
  • Each affected package's CHANGELOG.md has an entry. rn-forge-django's entry is marked breaking: BaseModelViewSet answers an application/json PATCH with 415.
  • The root and package sites build under --strict.
  • The scaffold tests (F9.8) serve each package's conformance fixture from built wheels. Each scaffold driver creates and resets /conformance/documents/1 the way its test_conformance.py does, and the scaffold suite (uv run pytest -m scaffold) passes.

Acceptance

set -euo pipefail
absent() { local rc=0; rg -q --hidden --glob '!.git' "$@" </dev/null || rc=$?; [ "$rc" -eq 1 ]; }

grep -q 'merge_patch' packages/rn-forge-web/src/rn_forge/web/__init__.py                  # S12.14.2
absent 'django|fastapi|starlette' packages/rn-forge-web/src/rn_forge/web/merge_patch.py   # S12.14.2
(cd packages/rn-forge-web && uv run pytest -q tests/test_merge_patch.py tests/test_conformance.py)   # S12.14.2, S12.14.3
grep -q '"patch"' packages/rn-forge-web/src/rn_forge/web/conformance/types.py             # S12.14.3
grep -q 'id="patch\.' packages/rn-forge-web/src/rn_forge/web/conformance/cases.py        # S12.14.3
absent 'pytest.skip' packages/rn-forge-django/tests/test_conformance.py packages/rn-forge-fastapi/tests/test_conformance.py  # S12.14.3
(cd packages/rn-forge-django && uv run pytest -q tests/drf/test_merge_patch.py tests/test_conformance.py)  # S12.14.4, S12.14.6
(cd packages/rn-forge-fastapi && uv run pytest -q tests/test_merge_patch.py tests/test_conformance.py)     # S12.14.5, S12.14.6
uv run pyright                                                    # S12.14.2, S12.14.4, S12.14.5
uv run lint-imports                                                    # S12.14.2, S12.14.4, S12.14.5
for pkg in web django fastapi; do
  grep -qi 'merge' "packages/rn-forge-$pkg/CHANGELOG.md"                                  # S12.14.6
  (cd "packages/rn-forge-$pkg" && uv run --group docs mkdocs build --strict -q --site-dir "$(mktemp -d)")   # S12.14.6
done
grep -qi 'breaking' packages/rn-forge-django/CHANGELOG.md                                 # S12.14.6
uv run pytest -q -m scaffold                                                             # S12.14.6

S12.14.1's search result and any dependency approval are read from Design.

Considered and rejected

  • Rejecting read-only members with a 422. This is the strictest option, but it breaks a client that sends back a representation it read. It also differs from DRF's and pydantic's defaults, so each adapter would need its own detection.
  • null on a field resets it to the column default. Hard to predict, because the default can live on the model, the serializer or the database. It also differs between the two stacks.
  • null removes the member, as RFC 7396 says for documents. On a fixed-schema resource, DRF's full update then skips the field, so the stored value silently stays.
  • Accepting application/json on PATCH as a merge patch. The media type is how a client says which semantics it wants. RFC 5789 §2.2 has the server refuse a patch format it does not support, and name the ones it does in Accept-Patch.
  • JSON Patch (RFC 6902). The API conventions chose merge patch. JSON Patch's operation list is harder for a form-based client to produce and gives no benefit for flat resources.