# A PATCH that returns 200 can still wipe a client's data

> Every API has its own way of saying "delete", and a sync job that mistranslates one can erase customer records without raising a single error.

Original: https://fdetimes.net/en/guides/patch-null-semantics-data-loss/

When you update a customer on Stripe, sending an empty value for `metadata` removes every metadata key on that customer. HubSpot's documentation (the legacy branch) says that to clear the value of a CRM property you send an empty string. In JSON Merge Patch (RFC 7396), the value that means "remove" is `null`.

That is three systems with three ways of saying "delete this". Most of the integrations an FDE writes sit between systems like these: reading from a client's CSV file, ERP or internal form, then pushing into a CRM, a billing system or an HR directory.

If the code confuses "no value yet", "empty value" and "leave this alone", an overnight sync job can delete a client's data without anyone noticing.

The danger is that the bug throws no exception. The API returns 200, the logs stay clean and the dashboard stays green, until the client's sales team discovers that thousands of phone numbers have vanished.

The skill required is narrow but valuable: knowing exactly how the target API interprets each state of a field, and keeping those states intact through the whole pipeline.

## Every field carries one of three intents

When you update a record, each field you send carries one of three intents: keep it, clear it, or set a new value. On the first intent, most APIs agree.

Stripe states that parameters not sent are left unchanged. Microsoft Graph likewise says properties not included in the body keep their previous values, or are recalculated based on changes to other properties.

Zalando's API guidelines describe JSON Merge Patch with the same logic: `null` explicitly signals that a property should be removed, while absent properties are ignored and left unmodified. Where APIs diverge is in how they say "clear".

Even within a single API there are exceptions. Microsoft Graph specifies that when you update the nested object `employeeOrgData`, omitting either of its two properties sets that property to null. In that one place, leaving a field out means deleting it.

Protobuf is trickier still. Its documentation says that for fields with implicit presence there is no signal to distinguish a field that was never set from one set to 0, so resetting a field to its default requires an external mechanism such as a FieldMask.

Google's AIP-134 adds that if the client sends no field mask, the service must treat the mask as covering every field that has a value. Without a mask, then, you cannot set a field to 0, because the service will read it as a field you did not touch.

| Target API | Keep | Clear | Trap to remember |
|---|---|---|---|
| JSON Merge Patch (RFC 7396) | Leave the field out of the body | Send `null` | Cannot modify part of an array |
| Stripe, update customer | Do not send the parameter | Empty value for each metadata key | An empty value for all of `metadata` removes every key |
| HubSpot, update object (legacy) | Not stated in the docs; verify on a sandbox | Empty string | A blank CSV cell becomes a delete command |
| Microsoft Graph, update user | Leave it out of the body | Not stated in the docs; verify on a sandbox | An omission inside `employeeOrgData` becomes null |
| Protobuf under AIP-134 | Do not send it; keep it out of the mask | Reset to default via FieldMask | Without a mask you cannot set a value to 0 |

## The bug hides in the most harmless-looking line

Take a hypothetical case. A client sends a CSV of contacts in which some rows fill in only the email column, and your job pushes each row to a CRM that accepts JSON Merge Patch. The Pydantic model is typically written like this:

```python
from typing import Optional
from pydantic import BaseModel

class ContactUpdate(BaseModel):
    phone: Optional[str] = None
    email: Optional[str] = None
    company: Optional[str] = None

row = {"email": "an@acme.example"}   # CSV row with only an email
patch = ContactUpdate(**row)

patch.model_dump()
# {'phone': None, 'email': 'an@acme.example', 'company': None}

patch.model_dump(exclude_unset=True)
# {'email': 'an@acme.example'}
```

The first `model_dump()` line looks perfectly ordinary. Under Merge Patch, however, the two `None` values for `phone` and `company` are serialized as `null`, which makes them two delete commands. You meant to change the email and ended up wiping the phone number and the company name as well.

FastAPI recommends exactly this fix: use `exclude_unset` so that only the values the user actually sent are updated, rather than overwriting stored data with the model's defaults.

Filtering out unset fields solves only half the problem. The other half is that when you genuinely want to clear something, the clear command has to be written the way the target API expects. Put that in a function of its own:

```python
CLEAR = object()  # the "clear" intent, kept distinct from None

def encode(fields: dict, target: str) -> dict:
    out = {}
    for key, value in fields.items():
        if value is CLEAR:
            if target == "merge_patch":      # RFC 7396
                out[key] = None
            elif target == "hubspot_legacy":
                out[key] = ""
            else:
                raise ValueError(f"Don't know how to clear {key} on {target}")
        else:
            out[key] = value
    return out
```

The `raise` branch is the most important part of the function. When it meets a target API that has not been verified, the job stops and reports an error instead of guessing and quietly deleting data.

## Arrays, nested objects and atomicity

RFC 7396 is explicit that Merge Patch cannot modify part of anything that is not an object, such as replacing a few elements of an array. If the source system sends only new tags and you PATCH the `tags` array directly, every existing tag is replaced. For arrays, read the current record, merge in code, and only then send the whole array.

Nested objects require reading the documentation field by field, because, as the `employeeOrgData` example shows, an API's general rule can be reversed for a specific field. When nested objects are involved, always send every sub-property.

RFC 5789 requires the server to apply the full set of changes in a PATCH atomically. That protects you from half-updated records, but it does nothing when the intent is wrong. A field that has slipped into `null` will be applied just as neatly as the correct ones.

**Key point:** A safe sync job must be able to tell "leave this alone" from "delete this".

## How to handle it on a client site

Start with a question for the client before writing any code: does a blank cell in your file mean "unknown" or "removed"? The answer often differs from column to column, and it belongs in the mapping document. Then build a table like the one above for the specific target API, using only its official documentation.

In code, preserve the three states with `exclude_unset` plus a dedicated sentinel for the clear intent, and encode for each target API in exactly one place. For arrays and nested objects, read and merge before writing. Finally, test on a sandbox with a record that has every field filled in: PATCH one field, then assert that every other field is unchanged.

If you get a say in API design, remember why Google prefers PATCH to PUT: with PUT, adding a new field to an existing resource becomes a breaking change. Older clients do not know about the new field, so they send a body without it, and the new data can be overwritten.

## The mistakes that keep recurring

The most common mistake is treating Python's `None`, JSON's `null` and a blank CSV cell as the same thing. The second is reading one API's documentation and assuming another behaves the same way: run code written for Merge Patch against HubSpot and empty strings will delete data.

The third is testing only on empty records, where every accidental deletion leaves no trace.

The fourth is harder to spot: sending Protobuf without a field mask and wondering why a field cannot be set to 0. Under AIP-134, the service is behaving exactly as specified.

## Show employers you understand this

This skill deserves its own line on a CV, written as a concrete action, for example "designed sync jobs that preserve keep/clear/update semantics, with regression tests against data loss".

In an integration design interview, ask "what does a blank cell mean?" early on, so the interviewer sees that you know where the risk of data loss lies.

## This week's exercise

Pick an API your client writes data into. Build a three-column table, Keep / Clear / Trap, from that API's official documentation alone, then prove each cell with a real request on a sandbox against a record with every field filled in. Wherever you cannot yet prove a cell, your `encode` function should `raise` at exactly that cell.

**Try this week:**

- Pick an API your client writes into and build a three-column Keep / Clear / Trap table from that API's official documentation alone
- Search the integration codebase for every call to model_dump() or dict() ahead of a PATCH and check whether exclude_unset is missing
- Write a test: create a sandbox record with every field filled in, PATCH one field, then assert that every other field is unchanged

## Sources

- [RFC 7396: JSON Merge Patch](https://www.rfc-editor.org/rfc/rfc7396.html)

- [RFC 5789: PATCH Method for HTTP](https://www.rfc-editor.org/rfc/rfc5789.html)

- [AIP-134: Standard methods: Update](https://google.aip.dev/134)

- [Field Presence (Protocol Buffers Documentation)](https://protobuf.dev/programming-guides/field_presence/)

- [Update a customer (Stripe API Reference)](https://docs.stripe.com/api/customers/update)

- [HubSpot API reference: update object (legacy)](https://developers.hubspot.com/docs/api-reference/legacy/crm/objects/objects/update-object)

- [Update user - Microsoft Graph v1.0](https://learn.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0)

- [Body - Updates (FastAPI)](https://fastapi.tiangolo.com/tutorial/body-updates/)

- [Zalando RESTful API and Event Guidelines](https://opensource.zalando.com/restful-api-guidelines/)
