There has been some debate about when to use PUT versus PATCH versus POST in REST APIs. Having dealt with a variety of 3rd-party REST APIs now, I've become a little opinionated about how the various methods *should* be used. Here's my take:
The way I prefer to see PUT used is to submit a fully-formed replacement resource. In other words, if you are using PUT to update a resource, you probably will want to fetch the object from the resource initially, modify it and then PUT the entire modified object back to the resource. If you are creating a new resource, use PUT only if you are creating your own resource ID (probably not a common use-case, since most resources will auto-assign their own IDs).
In contrast, PATCH can update any number of properties of a known resource without needing to submit the entirety of the resource. In most cases, PATCH is the right method for updates as it saves on bandwidth.
IMO, POST is the right method for creating a new resource, assuming IDs are auto-assigned. Note that POST doesn't need to know every property of a resource in order to create a new one, whereas PUT must. So if your client wants to start a transaction, for example, POST means they don't need to submit every property of a transaction to create one. It makes life much easier on your client.
What this boils down to for me is that PUT should used only rarely for specific use-cases.
The way I prefer to see PUT used is to submit a fully-formed replacement resource. In other words, if you are using PUT to update a resource, you probably will want to fetch the object from the resource initially, modify it and then PUT the entire modified object back to the resource. If you are creating a new resource, use PUT only if you are creating your own resource ID (probably not a common use-case, since most resources will auto-assign their own IDs).
In contrast, PATCH can update any number of properties of a known resource without needing to submit the entirety of the resource. In most cases, PATCH is the right method for updates as it saves on bandwidth.
IMO, POST is the right method for creating a new resource, assuming IDs are auto-assigned. Note that POST doesn't need to know every property of a resource in order to create a new one, whereas PUT must. So if your client wants to start a transaction, for example, POST means they don't need to submit every property of a transaction to create one. It makes life much easier on your client.
What this boils down to for me is that PUT should used only rarely for specific use-cases.
Comments
Post a Comment