Monday, November 4, 2019

PUT vs POST

The HTTP specification provides us with two verbs that confuse me pretty much every time I have to think about them: PUT and POST. Since I found a really good answer on SO for the difference between them and when to use each one, I thought I'd write up a blog post, include that link, and remind myself when I use each one.

Anyway, here's the answer I found that I like.

As far as when I use each one, I use POST when I'm creating new resources and don't want to specify their exact location (and I never specify the exact location when I send data to the server because I usually want the server or the database to generate an ID that will be used to identify the resource later). I use PUT when I'm replacing a known resource in its entirety. The HTTP spec defines that a PUT request must make no assumptions about what the caller wants, and should just take what was provided by the caller and apply it to the resource at that address. I use POST to update part of a known resource without replacing the whole thing.

Update: I've started using PATCH more often for updating parts of a resource without updating or replacing the entire thing. This is more semantically correct than using POST. I'll try to remember to update this with an actual code example of doing that once I figure out how I want it all to work.

Update 2: It turns out I've been using PATCH wrong. Per the spec PATCH requests are supposed to include a list of instructions on how the object should be patched. I found this article that helped me see the light, then these instructions for implementing PATCH "properly" in dotnet 5. I'll try to put up a full example when I get it all working and have time.

Update 3: I found time.

POST: /cars (to create a new car resource)
PUT: /cars/{id} (to replace the car resource with that ID)
POST: /cars/{id} (to update the car resource with that ID, but not replace it)
PATCH: /cars/{id} (to update some pieces of the car, but ignore everything that isn't present)

No comments:

Post a Comment