0

how exactly http methods work.

the both view function do the same thing

django code:

//post method
def create1_post(request):
   if request.method=="POST":
      any_model=AnyModel(title="example")
      any_model.save()

//put method
def create2_post(request):
   if request.method=="PUT":
      any_model=AnyModel(title="example")
      any_model.save()



I read a lot about http methods ,But all I learned is PUT method is for update or create resource and POST method is for create resource

Now I am confused . if I can edit and create models with python why I need to use put or any other http methods

  • 1
    A POST query is often done to *create* something, whereas PUT specifies *where* to put it, so for what primary key. As a result PUT is idempotent whereas POST isn't. – Willem Van Onsem Oct 16 '21 at 11:47
  • 1
    The programmer should thus implement handlers for a HTTP requests according to the specifications: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 for example a GET request is *not* supposed to have side-effects. – Willem Van Onsem Oct 16 '21 at 11:48
  • The HTTP methods are just providing abstract rules that how a service needs to be exposed, you can use POST or PUT for insert operation just thing is it is easy to distinguish that POST will be used to do something with insert and PUT will be used to do something with update related queries. These rules impose just some good practice as we are separating our logic into small manageable parts. Otherwise its call of developer whether he wants to use POST or PUT. – k33da_the_bug Oct 16 '21 at 13:02

1 Answers1

2

According to the HTTP specification the PUT method is intended for idempotent operations. Meaning that a PUT request can be sent once or several times and the change on the server will be the same in both cases.

The typical example is POST being used to create objects, and PUT being used to update existing objects. Sending a POST twice creates two new objects, sending PUT twice just updates an object to the same state twice.

It is important to consider this difference and use the correct HTTP verb since the assumption of idempotency is used by browsers and frameworks for caching purposes.