Many people struggle to choose between HTTP PUT vs POST methods when designing a system. Let?s try to solve the puzzle when to use PUT or POST. Once of the best approaches is to choose the behaviuour based on idempotence of the action.
HTTP PUT
PUT puts a file or resource at a specific URI, and exactly at that URI. If there?s already a file or resource at that URI, PUT should replace that file or resource. If there is no file or resource there, PUT creates one. PUT is idempotent. It means that can be used several times without different outcomes. It would not matter if it is used only once, or ten times over. The result should be the same. Again, this only applies to the result, not the resource itself. Paradoxically PUT responses are not cacheable.
For example ?PUT /books/5? would have to either create a new book with the id of 5, or replace the existing book with ID 5.
HTTP POST
POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not idempotent, however POST responses are cacheable so long as the server sets the appropriate Cache-Control and Expires headers.
Following the same example of books as before, ?POST /books? with a bunch of book information might create a new book, and respond with the new URL identifying the id of that book.
Difference between PUT and POST
The RFC itself explains the core difference:
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request ? the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
Other related articles:
Introduction to RESTful API Design
When designing API endpoints, there?s always the need to specify what http method to use for CRUD (Create?
medium.com
Development: How Two Way SSL (2WSSL) works
Development: How Two Way SSL (2WSSL) works
Development: How Two Way SSL (2WSSL) worksmedium.com
Development: Difference between the http requests POST and GET
The GET and POST are two different types of HTTP requests.
medium.com
Development: SOAP vs REST
SOAP and REST can?t be compared directly, since the first is a protocol and the second is an architectural style.
medium.com
Via: