Open In App

PUT method – Python requests

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make PUT request to a specified URL using requests.put() method. Before checking out the PUT method, let’s figure out what a Http PUT request is – 
 

PUT Http Method

PUT is a request method supported by HTTP used by the World Wide Web. The PUT method requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI. 
 

How to make PUT request through Python Requests

Python’s requests module provides in-built method called put() for making a PUT request to a specified URI.
Syntax – 
 

requests.put(url, params={key: value}, args)

Example – 
Let’s try making a request to httpbin’s APIs for example purposes. 
 

Python3




import requests
 
# Making a PUT request
r = requests.put('https://httpbin.org / put', data ={'key':'value'})
 
# check status code for response received
# success code - 200
print(r)
 
# print content of request
print(r.content)


save this file as request.py and through terminal run, 
 

python request.py

Output –
 

put-request-pytohn-requests

 

Difference between PUT and POST methods

 

PUT POST

PUT request is made to a particular resource. If the Request-URI refers to an already existing resource, an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier). 
Example – 
 

PUT /article/{article-id}

 

POST method is used to request that the origin server accept the entity enclosed in the 
request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI. 
Example – 
 

POST /articles

 

PUT method is idempotent. So if you send retry a request multiple times, that should be equivalent to single request modification. POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.
Use PUT when you want to modify a single resource which is already a part of resources collection. PUT overwrites the resource in its entirety. Use PATCH if request updates part of the resource. 
 
Use POST when you want to add a child resource under resources collection.
Generally, in practice, always use PUT for UPDATE operations. Always use POST for CREATE operations.

 


Last Updated : 22 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads