A thoughtful technical blog

Menu

Tag Archives: rest

I have been looking into implementing partial updates using the HTTP PATCH method using ServiceStack.net and the JSON Patch format (RFC 6902)

This is of interest since many updates do not neatly match the PUT method, which often is used for full entity updates (all properties). PATCH is intended to do one or more partial updates. There are a fewblogsdescribing the use cases.

I’ve been happy using ServiceStack the way it was designed – RESTful, simple, using Message Based designs.

I could implement PATCH using my own message format – that is easy to do. Usually it would be the actual DTO properties, plus a list of fields which are actually going to be updated. You wouldn’t update all fields, and you don’t want to only update non-null properties, since sometimes “null” is a valid value for a property (it would be impossible to set a property to null from non-null).

In my opinion, using JSON Patch for the Request body has pros and cons.
Pros:

is an official RFC

covers a lot of use cases

Cons:

very generic, so we lose some of the benefit of strong typing

doesn’t have a slot for the Id of a resource when calling PATCH /employees/{Id}

doing this the “JSON Patch way” would be { “op”: “replace”, “path”: “/employees/123/title”, “value”: “Administrative Assistant” } , but that wastes the value of having it on the routing path.

JSON Patch supports a handful of operations: “add”, “remove”, “replace”, “move”, “copy”, “test”. I will focus on the simple “replace” op, since it easily maps to replacing a property on a DTO (or field in a table record).

I’m going to ignore the If-Match: / ETag: headers for now. Those will be useful if you want to tell the server to only apply your changes if the resource still matches your “If-Match” header (no changes in the meantime). “That exercise is left to the reader.”

Let’s say we have a more practical example:

an Employee class, backed by an [Employee] table, accessed by OrmLite

an EmployeeService class, implementing the PATCH method

the Request DTO to the Patch() method aligns to the JSON Patch structure

The Employee class would simply look like this (with routing for basic CRUD):

But how do we get the #$%&& Id from the route?? This code throws RequestBindingException! But i can’t change the shape of the PATCH request body from a JSON array [].
The answer was staring me in the face: just add it to the DTO class definition, and ServiceStack will map to it. I was forgetting the C# class doesn’t have to be the same shape as the JSON.

The only wrinkle is all the JSON values come in as C# string, even if they are numeric or Date types. At least you will know the strong typing from your C# class, so you know what to convert to.

My full Patch() method is below– note the partial update code uses reflection to update properties of the same name, and does primitive type checking for parsing the string values from the request DTO.