Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same representation for GET and PUT?

Tags:

rest

http

As other people (for example: here) I'm struggling with the question, if the representation for GET and PUT should be the same?

Example:

GET representation:

{
    "id": "0815",
    "name": "jdoe",
    "emailAddress": "[email protected]",
    "displayName": "John Doe",
    "active": true
}

PUT representation:

{
    "emailAddress": "[email protected]",
    "displayName": "John Doe"
}

Research:

I read in REST question: PUT one representation, GET a different one? that it is ok, to get another media type with GET as I saved with PUT.

I read in REST - put IDs in body or not? that it is ok, to omit the id with PUT and get the id with GET.

I read in GET Representation != POST Representation that it is ok, to omit a lot of properties with PUT and get them with GET. An example is JIRA REST API - api/2/myself. GET returns the hole user model and PUT saves only 3 properties.

Is that good practice? I could also use PATCH, for example GitHub REST API - users. What's the reason to add PATCH to HTTP, if PUT with another smaller representation is already enough?

Further more I read in Best practice for partial updates in a RESTful service that most big REST APIs (for example: Google) use PATCH or POST for partial updates and PUT only for complete/full updates (for example: Goolge - Updating an entity).

like image 606
dur Avatar asked Mar 13 '23 16:03

dur


1 Answers

The idea is that the server generally has more information about the resource than the user, and so GET might return more information than is required for PUT. There are some things which the server 'owns', and so cannot be updated by the client. These can be returned by GET while the PUT representation does not allow the user to modify them.

However, that's not the same thing as saying that PUT allows you to partially update the resource. When you PUT a document you update all of the values which that document covers - so an 'optional' value which is not present in the actual document sent via PUT should be removed from the resource. When you do a subsequent GET on that resource, the optional value will not be present.

The semantics of PATCH are supposed to be slightly different - with PATCH the client sends a partial update which describes changes in some way. Those changes are then applied to the resource in some fashion. Parts of the resource which are not mentioned in the document sent via PATCH will be unmodified.

Also, note that PATCH is explicitly defined as neither safe nor idempotent. Whereas PUT is idempotent but not safe - the same request repeated will result in the same change. With a PATCH, some changes could be cumulative (e.g. add a value to a list) and so duplicated requests could result in a different state of the resource.

like image 74
sisyphus Avatar answered Apr 19 '23 10:04

sisyphus