According to my knowledge:
PUT
- update object with its whole representation (replace)PATCH
- update object with given fields only (update)
I'm using Spring to implement a pretty simple HTTP server. When a user wants to update his data he needs to make a HTTP PATCH
to some endpoint (let's say: api/user
). His request body is mapped to a DTO via @RequestBody
, which looks like this:
class PatchUserRequest {
@Email
@Length(min = 5, max = 50)
var email: String? = null
@Length(max = 100)
var name: String? = null
...
}
Then I use an object of this class to update (patch) the user object:
fun patchWithRequest(userRequest: PatchUserRequest) {
if (!userRequest.email.isNullOrEmpty()) {
email = userRequest.email!!
}
if (!userRequest.name.isNullOrEmpty()) {
name = userRequest.name
}
...
}
My doubt is: what if a client (web app for example) would like to clear a property? I would ignore such a change.
How can I know, if a user wanted to clear a property (he sent me null intentionally) or he just doesn't want to change it? It will be null in my object in both cases.
I can see two options here:
- Agree with the client that if he wants to remove a property he should send me an empty string (but what about dates and other non-string types?)
- Stop using DTO mapping and use a simple map, which will let me check if a field was given empty or not given at all. What about request body validation then? I use
@Valid
right now.
How should such cases should be properly handled, in harmony with REST and all good practices?
EDIT:
One could say that PATCH
shouldn't be used in such an example and I should use PUT
to update my User. But then what about API updates (adding a new property for example)? I would have to version my API (or version user endpoint alone); after every User change, api/v1/user
, which accepts PUT
with an old request body, api/v2/user
which accepts PUT
with a new request body, etc. I guess it's not the solution and PATCH
exists for a reason.
TL;DR
patchy is a tiny library I've come up with that takes care of the major boilerplate code needed to properly handle
PATCH
in Spring i.e.:Simple solution
Since
PATCH
request represent changes to be applied to the resource we need to model it explicitly.One way is to use a plain old
Map<String,Any?>
where everykey
submitted by a client would represent a change to the corresponding attribute of the resource:The above is very easy to follow however:
The above can be mitigated by introducing validation annotations on the domain layer objects. While this is very convenient in simple scenarios it tends to be impractical as soon as we introduce conditional validation depending on the state of the domain object or on the role of the principal performing a change. More importantly after the product lives for a while and new validation rules are introduced it's pretty common to still allow for an entity to be update in non user edit contexts. It seems to be more pragmatic to enforce invariants on the domain layer but keep the validation at the edges.
This is actually very easy to tackle and in 80% of cases the following would work:
Validating the request
Thanks to delegated properties in Kotlin it's very easy to build a wrapper around
Map<String,Any?>
:And using
Validator
interface we can filter out errors related to attributes not present in the request like so:Obviously we can streamline the development with
HandlerMethodArgumentResolver
which I did below.Simplest solution
I thought that it would make sense to wrap what've described above into a simple to use library - behold patchy. With patchy one can have a strongly typed request input model along with declarative validations. All you have to do is to import the configuration
@Import(PatchyConfiguration::class)
and implementPatchyRequest
interface in your model.Further reading
What I do in some of the applications is create an
OptionalInput
class which can distinguish whether a value is set or not:Then in your request class:
The properties can be validated by creating a
@OptionalInputLength
.Usage is:
NOTE: The code is written in
groovy
but you get the idea. I've used this approach for a few APIs already and it seems to be doing it's job quite well.As you noted the main problem is that we don't have multiple null-like values to distinguish between explicit and implicit nulls. Since you tagged this question Kotlin I tried to come up with a solution which uses Delegated Properties and Property References. One important constraint is that it works transparently with Jackson which is used by Spring Boot.
The idea is to automatically store the information which fields have been explicitly set to null by using delegated properties.
First define the delegate:
This acts like a proxy for the property but stores the null properties in the given
MutableSet
.Now in your
DTO
:Usage is something like this:
This works because Jackson explicitly calls
user.setName(null)
in the second case and omits the call in the first case.You can of course get a bit more fancy and add some methods to an interface which your DTO should implement.
Which makes the checks a bit nicer with
user.isExplicitNull(User::name)
.I have had the same problem, so here are my experiences / solutions.
I would suggest that you implement the patch as it should be, so if
If you don't do that, you'll soon get an api which is hard to understand.
So I would drop your first option
The second option is actually a good option in my opinion. And that is also what we did (kind of).
I'm not sure if you can make the validation properties work with this option, but then again, should this validation not be on your domain layer? This could throw an exception from the domain which is handled by the rest layer and translated into a bad request.
This is how we did it in one application:
The json deserializer will instantiate the PatchUserRequest but it will only call the setter method for fields that are present. So the contains boolean for missing fields will remain false.
In another app we used the same principle but a little different. (I prefer this one)
You could also do the same by letting your PatchUserRequest extend Map.
Another option might be to write your own json deserializer, but I haven't tried that myself.
I don't agree with this. I also use PATCH & PUT the same way as you stated: