Thursday, July 15, 2021

Patch with JsonPatchDocument in dotnet 5

As I mentioned recently in an update to my PUT vs POST... post, I've been using PATCH all wrong for a long time. It turns out the spec for PATCH says you're supposed to send a set of instructions for how the server should modify an existing resource.

With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

That seems easy enough, I guess. Just tell the server, using a particular format, how to change the resource. And it is easy enough. But I ran into a small problem that took me way too long to solve so I'm writing it up.

I'm communicating from an Angular app to a dotnet 5 Web API. Here are some surprisingly good instructions for consuming a JsonPatchDocument on the server in my scenario. On the front-end I decided not to use a library and instead just send up the JSON in the expected format, like this:

const patch = {op: 'replace'path: `/firstName`value: 'Fred'as JsonPatchDocument;

That should have worked (so I thought), but it didn't. My JsonPatchDocument<Person> was resolving to null instead of a JsonPatchDocument. Eventually, I stumbled on a github issue for a totally separate library that I'm not using and one of the comments said this: "A correct JSONPatch body must contain an array of operations." Which, in hindsight, duh. The solution ended up being super simple: just send an array containing my single operation instead of sending the single operation.

Other than that small issue, Microsoft's instructions were spot on. I guess technically their instructions were spot on and I just overlooked that detail. Hopefully this helps you (or future me).