DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Please ELI5 about POST / PUT / PATCH best practices

It might be

  • POST - Create NEW record
  • PUT - If the record exists, update else, create a new record
  • PATCH - update
  • GET - read
  • DELETE - delete

But, do you really ever use PUT requests?

Also, we have to consider which can have req.body. To my understandings, GET and DELETE shouldn't have BODY, so mine becomes

  • GET - Simple query, like ?id={id}
  • POST - Complex query that needs req.body / file upload
  • PUT - Create NEW record
  • PATCH - Update
  • DELETE - Delete

Another thing to consider, IDEMPOTENCY. Do I have care about it?

HTTP  Idempotency
GET     yes
POST    no
PUT     yes
PATCH   no*
OPTIONS yes
HEAD    yes
DELETE  yes
Enter fullscreen mode Exit fullscreen mode

Why can't we use POST for everything?

Also, don't forget that there are also HEAD and OPTIONS.

Top comments (7)

Collapse
 
brandinchiu profile image
Brandin Chiu

The official HTTP spec does not explicitly prohibit DELETE requests from having a body.

This is a fairly heated topic among some developers, and can be quite controversial from the conversations I've been apart of.

The major benefit of adhering to an official spec is not for us. It's for everyone else who may want to work with our interfaces/apis. It creates am expected action/result flow that makes the process cleaner.

PUT is still a valuable way to identify paths to update your resources, as POST should not be used to do this.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

PUT is still a valuable way to identify paths to update your resources, as POST should not be used to do this.

Thanks.

Collapse
 
matthewbdaly profile image
Matthew Daly

Why can't we use POST for everything?

Because going with the grain of HTTP means things like HTTP caching are more likely to work as expected. If your site is behind a caching proxy like Varnish, then using the correct HTTP methods means it's more likely to "just work" as expected because Varnish knows what each one does and can act accordingly. You can work around this by writing your own rules, but why do that if you don't have to?

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt
Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

I should try varnish-cache.org/ someday, especially if I use AWS or DigitalOcean.

Collapse
 
matthewbdaly profile image
Matthew Daly

You should also bear in mind that some users may be behind a proxy you don't control, such as if their employer uses a web proxy like Squid to reduce the bandwidth used.

Collapse
 
augustocb23 profile image
Augusto César

I use...
Post: new registry
Put, passing id on path: update
Patch, id on path: partial update. Changing only a few fields