Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST vs PUT vs DELETE [duplicate]

Tags:

http

I never really understood why do I need the PUT and Delete request methods.

In my code I'm using all the time post and just do the backend code to add/delete something.

Am I doing this wrong or is it ok to use POST all the time?

My example:

  @RequestMapping(value = "/delete-images", method = RequestMethod.POST)
public @ResponseBody void deleteImages(@RequestParam("imageIDs") String[] imageIDs) {
    Docker.deleteImages(imageIDs);
}

2 Answers

The idea of REST is that you design your endpoints in a certain way, to represent the logical structure of the things you manipulate, then you use HTTP verbs to express what type of manipulation you're performing.

So for example rather than having /get-image?imageId=X and /delete-image?imageId=X endpoints, you should have just an /image/X endpoint (notice the absence of query parameters), and then the verbs GET/PUT/DELETE encode what you actually want to do with the image.

There are plenty of advantages of this approach (caching, standard tools, etc.), but there are two caveats:

  1. Not every data/operation fits this hierarchical resource model required by REST. Trying to squeeze it in regardless may result in very awkward APIs. (One example of something that doesn't quite fit is bulk operations.)
  2. The two things (URLs identify actual resources and verbs are used to identify operations) work in tandem, one without the other makes little sense.
like image 156
biziclop Avatar answered Sep 03 '25 00:09

biziclop


It's all about the semantics of the request. From the RFC 7231:

The request method token is the primary source of request semantics; it indicates the purpose for which the client has made this request and what is expected by the client as a successful result.

Here's a brief description of some HTTP methods defined in the RFC 7231 (click the links to check the full method definition):

  • GET: Transfer a current representation of the target resource.
  • HEAD: Same as GET, but only transfer the status line and header section.
  • POST: Perform resource-specific processing on the request payload.
  • PUT: Replace all current representations of the target resource with the request payload.
  • DELETE: Remove all current representations of the target resource
like image 45
cassiomolin Avatar answered Sep 03 '25 00:09

cassiomolin