Advanced Lesson 3
HTTP Requests
Chapter 4: HTTP request methods
PUT request
Another useful HTTP method is PUT, which is usually used to update an existing resource.
Let’s say you want to change the title of the article you just posted earlier to "We love snake puns"
. We will do that easily with the PUT method. This time, we use the endpoint http://localhost:5000/articles/11
. When used with the PUT method, this endpoint will update the given article (ID 11).
>>> updated_article = {"title": "We love snake puns"}
>>> response = requests.put("http://localhost:5000/articles/11", data=updated_article)
>>> print(response.json())
{'author': 4, 'content': 'What kind of car does a snake drive? An ana-honda.', 'id': 11, 'title': 'We love snake puns'}
Notice that we only updated the title. The server correctly retrieved the correct article and updated it accordingly. Like our POST example, the API also provided an acknowledgement that the operation has succeeded by returning the updated resource itself.
As a sanity check, we will retrieve the same article with GET again.
>>> response = requests.get("http://localhost:5000/articles/11")
>>> print(response.json())
{'author': 4, 'content': 'What kind of car does a snake drive? An ana-honda.', 'id': 11, 'title': 'We love snake puns'}
Yes, the title is indeed the new title.