1

I've read PUT vs. POST in REST in full and also w3 docs but still not sure of what's the right approach.

If I want to turn on the heater:

POST /house/123/

{"appliance" : "heater" , "action" : "on"}

or

PUT /house/123/

{"appliance" : "heater" , "action" : "on"}

or I should be using some other method? I think neither of them solve the question at hand since there is no object creation happening here...

EDIT:

What if I it's just just turning on/off. Rather it's a reboot. Think of it as something that needs to happen. Doesn't necessarily need to be a change of state.

/house/123/

{"action" : "reboot-heater"}
mfaani
  • 33,269
  • 19
  • 164
  • 293

1 Answers1

3

Both methods are appropriate, in various circumstances.

POST is the universal method - you can use it for anything, although there are often better choices (ex: GET, when the operation is safe). HTML only supports GET and POST, and it is the lingua franca of the web. So you can infer that POST is fine.

PUT also works; it's analogous to "save", "replace", "upsert". The issue with PUT is that the semantics are that the request payload is a replacement for the current state of the target resource.

In effect, that means that

PUT /house/123/

{"appliance" : "heater" , "action" : "on"}

should be a complete replacement for the state of /house/123. That's probably not what you want, assuming the state of the house includes descriptions of other appliances, rooms, occupants, location, and so on.

You could PATCH the house, describing the change to the heater with a patch document. But that relaxes the idempotent semantics that are an important benefit of PUT.

You could also PUT to a different target resource - but that may not give you suitable caching behavior.

It's important, if you want to get the framing right in your head, to think about the fact that the resources are part of your integration domain. Your REST api is a disguise that your server wears, pretending to be a dumb HTTP key value store.

A good read, if you have time, is RESTful Casuistry, where a bunch of folks discuss what a RESTful protocol for requesting a server shutdown should be.

VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91