danielgtaylor / danielgtaylor/huma

Autopatch does not work with nullable fields

Open
#634 5 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Go
Stars
4.4k
Forks
285
Avg merge
40m
Merged PRs (30d)
1

Description

Consider a simple struct with two nullable string fields:
```
type Foo struct {
A *string `json:"a"`
B *string `json:"b"`
}
```
It is evidently impossible to set these fields to `nil` via a `PATCH` with `application/merge-patch+json` content type. For instance, the following request will throw a 422 with a message "expected required property a to be present".
```
curl --request PATCH \
--url http://localhost:8888/foo/1 \
--header 'Accept: application/json, application/problem+json' \
--header 'Content-Type: application/merge-patch+json' \
--data '{
"a": null
}'
```

This seems like a bug in merge patch computation: the `PUT` body in the autogenerated `GET`/`PUT` sequence omits the `a` field altogether instead of setting `a: null` as expected.

The only way to set `a` to `nil` appears to be via a `PUT` of the full struct or via a `json-patch` (not `merge-patch`):
```
curl --request PATCH \
--url http://localhost:8888/foo/1 \
--header 'Accept: application/json, application/problem+json' \
--header 'Content-Type: application/json-patch+json' \
--data '[
{ "op": "replace", "path": "/a", "value": null }
]
```
This came as an unfortunate surprise as our front-end client started making use of PATCH requests.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by reproducing the curl request with application/merge-patch+json against a struct containing nullable string fields, then trace the autogenerated GET/PUT sequence and its merge patch computation. Done means PATCH can set field a to null without the 422 required-property error, while the existing json-patch behavior remains intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.