Reputation: 827
Does it violate the ideas of REST, or accepted conventions, to have different models for GET/PUT/POST at the same URL?
An example:
Consider a simple resource found at api/things
I can create a thing by:
POST api/things
with body = { Name: "New Thing" }
This returns me a thing along with location
{ Id: 500, Name: "New Thing", Links: ["api/things/500"] }
Location Header: api/things/500
I can get the thing with:
GET api/things/500
and I will get
{ Id: 500, Name: "New Thing", Links: ["api/things/500"] }
If I want to update it: PUT api/things/500
{ Name: "Updated Thing", IsActive: false }
There are "rules" in this example that are hidden behind the different models.
One strong criticism of this: I cannot do a POST to create a new one, change the Name field, and PUT it back to Update it. I would have to know to remove the Id and links fields. I could "be liberal in what I accept" and allow the Ids and Links to be on the PUT request, but then I need to make additional decisions like, "is it a 400 if the Id/Link they send is different?, and "is it a 400 if they don't send an Id/Link?". If the API claims to accept those fields on PUT, that could be seen as a contract that they are able to be updated.
Upvotes: 5
Views: 2840
Reputation: 1893
It is perfectly valid to accept different DTO's for different methods. Quite often, a POST will create a new entity with default properties such as Id, StartDate or Active, etc. so these properties are not present on a "POST DTO". I tend to shy away from PUT's since the definition is you are replacing one entity with another, which could include an Id. I opt for PATCH in most cases where you are accepting deltas and partial objects. You can verify each property that was sent up and determine if it's a readonly property or not. In some cases, based on roles, it may be readonly for one user, and patchable by another. By following this, POST is one DTO, PATCH is partial, PUT is non-existent, and GET returns the full DTO.
I've only seen a couple places where PUT is useful. You want to change the binary of a file or you have a collection that you want to change, PUT is great. Otherwise, I love PATCH.
Upvotes: 10