Request Put Python

HTTP & SOCKS Rotating & Static Proxy

  • 72 million IPs for all purposes
  • Worldwide locations
  • 3 day moneyback guarantee


PUT method – Python requests – GeeksforGeeks

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 () method. Before checking out the PUT method, let’s figure out what a Http PUT request is – PUT Http MethodPUT 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. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level CourseHow to make PUT request through Python RequestsPython’s requests module provides in-built method called put() for making a PUT request to a specified – (url, params={key: value}, args)Example – Let’s try making a request to bin’s APIs for example purposes. Python3import requestsprint(r)print(ntent)save this file as and through terminal run, python Output – Difference between PUT and POST methodsPUTPOSTPUT 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 /articlesPUT method is idempotent. So if you send retry a request multiple times, that should be equivalent to single request is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on 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 nerally, in practice, always use PUT for UPDATE use POST for CREATE operations.
Quickstart — Requests 2.26.0 documentation


  • No logs
  • Kill Switch
  • 6 devices
  • Monthly price: $4.92


Quickstart — Requests 2.26.0 documentation

Eager to get started? This page gives a good introduction in how to get started
with Requests.
First, make sure that:
Requests is installed
Requests is up-to-date
Let’s get started with some simple examples.
Make a Request¶
Making a request with Requests is very simple.
Begin by importing the Requests module:
Now, let’s try to get a webpage. For this example, let’s get GitHub’s public
>>> r = (”)
Now, we have a Response object called r. We can
get all the information we need from this object.
Requests’ simple API means that all forms of HTTP request are as obvious. For
example, this is how you make an HTTP POST request:
>>> r = (”, data = {‘key’:’value’})
Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and
OPTIONS? These are all just as simple:
>>> r = requests. options(”)
That’s all well and good, but it’s also only the start of what Requests can
Passing Parameters In URLs¶
You often want to send some sort of data in the URL’s query string. If
you were constructing the URL by hand, this data would be given as key/value
pairs in the URL after a question mark, e. g.
Requests allows you to provide these arguments as a dictionary of strings,
using the params keyword argument. As an example, if you wanted to pass
key1=value1 and key2=value2 to, you would use the
following code:
>>> payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
>>> r = (”, params=payload)
You can see that the URL has been correctly encoded by printing the URL:
>>> print()
Note that any dictionary key whose value is None will not be added to the
URL’s query string.
You can also pass a list of items as a value:
>>> payload = {‘key1’: ‘value1’, ‘key2’: [‘value2’, ‘value3’]}
Response Content¶
We can read the content of the server’s response. Consider the GitHub timeline
>>> import requests
‘[{“repository”:{“open_issues”:0, “url”:”
Requests will automatically decode content from the server. Most unicode
charsets are seamlessly decoded.
When you make a request, Requests makes educated guesses about the encoding of
the response based on the HTTP headers. The text encoding guessed by Requests
is used when you access You can find out what encoding Requests is
using, and change it, using the r. encoding property:
>>> r. encoding
>>> r. encoding = ‘ISO-8859-1’
If you change the encoding, Requests will use the new value of r. encoding
whenever you call You might want to do this in any situation where
you can apply special logic to work out what the encoding of the content will
be. For example, HTML and XML have the ability to specify their encoding in
their body. In situations like this, you should use ntent to find the
encoding, and then set r. encoding. This will let you use with
the correct encoding.
Requests will also use custom encodings in the event that you need them. If
you have created your own encoding and registered it with the codecs
module, you can simply use the codec name as the value of r. encoding and
Requests will handle the decoding for you.
Binary Response Content¶
You can also access the response body as bytes, for non-text requests:
>>> ntent
b'[{“repository”:{“open_issues”:0, “url”:”
The gzip and deflate transfer-encodings are automatically decoded for you.
The br transfer-encoding is automatically decoded for you if a Brotli library
like brotli or brotlicffi is installed.
For example, to create an image from binary data returned by a request, you can
use the following code:
>>> from PIL import Image
>>> from io import BytesIO
>>> i = (BytesIO(ntent))
JSON Response Content¶
There’s also a builtin JSON decoder, in case you’re dealing with JSON data:
>>> ()
[{‘repository’: {‘open_issues’: 0, ‘url’: ‘
In case the JSON decoding fails, () raises an exception. For example, if
the response gets a 204 (No Content), or if the response contains invalid JSON,
attempting () raises requests. exceptions. JSONDecodeError. This wrapper exception
provides interoperability for multiple exceptions that may be thrown by different
python versions and json serialization libraries.
It should be noted that the success of the call to () does not
indicate the success of the response. Some servers may return a JSON object in a
failed response (e. g. error details with HTTP 500). Such JSON will be decoded
and returned. To check that a request is successful, use
r. raise_for_status() or check atus_code is what you expect.
Raw Response Content¶
In the rare case that you’d like to get the raw socket response from the
server, you can access If you want to do this, make sure you set
stream=True in your initial request. Once you do, you can do this:
>>> r = (”, stream=True)

>>> (10)
In general, however, you should use a pattern like this to save what is being
streamed to a file:
with open(filename, ‘wb’) as fd:
for chunk in er_content(chunk_size=128):
Using er_content will handle a lot of what you would otherwise
have to handle when using directly. When streaming a
download, the above is the preferred and recommended way to retrieve the
content. Note that chunk_size can be freely adjusted to a number that
may better fit your use cases.
An important note about using er_content versus
er_content will automatically decode the gzip and deflate
transfer-encodings. is a raw stream of bytes – it does not
transform the response content. If you really need access to the bytes as they
were returned, use
More complicated POST requests¶
Typically, you want to send some form-encoded data — much like an HTML form.
To do this, simply pass a dictionary to the data argument. Your
dictionary of data will automatically be form-encoded when the request is made:
>>> r = (“, data=payload)
“form”: {
“key2”: “value2”,
“key1”: “value1″},… }
The data argument can also have multiple values for each key. This can be
done by making data either a list of tuples or a dictionary with lists
as values. This is particularly useful when the form has multiple elements that
use the same key:
>>> payload_tuples = [(‘key1’, ‘value1’), (‘key1’, ‘value2’)]
>>> r1 = (”, data=payload_tuples)
>>> payload_dict = {‘key1’: [‘value1’, ‘value2’]}
>>> r2 = (”, data=payload_dict)
“key1”: [
“value2″]},… }
>>> ==
There are times that you may want to send data that is not form-encoded. If
you pass in a string instead of a dict, that data will be posted directly.
For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:
>>> import json
>>> url = ”
>>> payload = {‘some’: ‘data’}
>>> r = (url, (payload))
Instead of encoding the dict yourself, you can also pass it directly using
the json parameter (added in version 2. 4. 2) and it will be encoded automatically:
>>> r = (url, json=payload)
Note, the json parameter is ignored if either data or files is passed.
Using the json parameter in the request will change the Content-Type in the header to application/json.
POST a Multipart-Encoded File¶
Requests makes it simple to upload Multipart-encoded files:
>>> files = {‘file’: open(”, ‘rb’)}
>>> r = (url, files=files)
“files”: {
“file”: “<>“},… }
You can set the filename, content_type and headers explicitly:
>>> files = {‘file’: (”, open(”, ‘rb’), ‘application/’, {‘Expires’: ‘0’})}
If you want, you can send strings to be received as files:
>>> files = {‘file’: (”, ‘some, data, to, send\nanother, row, to, send\n’)}
“file”: “some, data, to, send\\nanother, row, to, send\\n”},… }
In the event you are posting a very large file as a multipart/form-data
request, you may want to stream the request. By default, requests does not
support this, but there is a separate package which does –
requests-toolbelt. You should read the toolbelt’s documentation for more details about how to use it.
For sending multiple files in one request refer to the advanced
It is strongly recommended that you open files in binary
mode. This is because Requests may attempt to provide
the Content-Length header for you, and if it does this value
will be set to the number of bytes in the file. Errors may occur
if you open the file in text mode.
Response Status Codes¶
We can check the response status code:
>>> atus_code
Requests also comes with a built-in status code lookup object for easy
>>> atus_code ==
If we made a bad request (a 4XX client error or 5XX server error response), we
can raise it with
Response. raise_for_status():
>>> bad_r = (”)
>>> bad_r. raise_for_status()
Traceback (most recent call last):
File “requests/”, line 832, in raise_for_status
raise _error
TPError: 404 Client Error
But, since our status_code for r was 200, when we call
raise_for_status() we get:
>>> r. raise_for_status()
All is well.
If a response contains some Cookies, you can quickly access them:
>>> r = (url)
>>> okies[‘example_cookie_name’]
To send your own cookies to the server, you can use the cookies
>>> cookies = dict(cookies_are=’working’)
>>> r = (url, cookies=cookies)
‘{“cookies”: {“cookies_are”: “working”}}’
Cookies are returned in a RequestsCookieJar,
which acts like a dict but also offers a more complete interface,
suitable for use over multiple domains or paths. Cookie jars can
also be passed in to requests:
>>> jar = questsCookieJar()
>>> (‘tasty_cookie’, ‘yum’, domain=”, path=’/cookies’)
>>> (‘gross_cookie’, ‘blech’, domain=”, path=’/elsewhere’)
>>> r = (url, cookies=jar)
‘{“cookies”: {“tasty_cookie”: “yum”}}’
Redirection and History¶
By default Requests will perform location redirection for all verbs except
We can use the history property of the Response object to track redirection.
The Response. history list contains the
Response objects that were created in order to
complete the request. The list is sorted from the oldest to the most recent
For example, GitHub redirects all HTTP requests to HTTPS:

>>> r. history
If you’re using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable
redirection handling with the allow_redirects parameter:
>>> r = (”, allow_redirects=False)
If you’re using HEAD, you can enable redirection as well:
>>> r = (”, allow_redirects=True)
You can tell Requests to stop waiting for a response after a given number of
seconds with the timeout parameter. Nearly all production code should use
this parameter in nearly all requests. Failure to do so can cause your program
to hang indefinitely:
>>> (”, timeout=0. 001)
File ““, line 1, in
requests. Timeout: HTTPConnectionPool(host=”, port=80): Request timed out. (timeout=0. 001)
timeout is not a time limit on the entire response download;
rather, an exception is raised if the server has not issued a
response for timeout seconds (more precisely, if no bytes have been
received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do
not time out.
Errors and Exceptions¶
In the event of a network problem (e. DNS failure, refused connection, etc),
Requests will raise a ConnectionError exception.
Response. raise_for_status() will
raise an HTTPError if the HTTP request
returned an unsuccessful status code.
If a request times out, a Timeout exception is
If a request exceeds the configured number of maximum redirections, a
TooManyRedirects exception is raised.
All exceptions that Requests explicitly raises inherit from
Ready for more? Check out the advanced section.
If you’re on the job market, consider taking this programming quiz. A substantial donation will be made to this project, if you find a job through this platform.
Is there any way to do HTTP PUT in python - Stack Overflow

Is there any way to do HTTP PUT in python – Stack Overflow

I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python?
asked Sep 21 ’08 at 20:11
AmandasaurusAmandasaurus50. 8k67 gold badges178 silver badges236 bronze badges
I’ve used a variety of python HTTP libs in the past, and I’ve settled on ‘Requests’ as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
payload = {‘username’: ‘bob’, ’email’: ”}
>>> r = (“, data=payload)
You can then check the response status code with:
or the response with:
Requests has a lot synactic sugar and shortcuts that’ll make your life easier.
answered Nov 24 ’11 at 15:54
import urllib2
opener = _opener(TPHandler)
request = quest(”, data=’your_put_data’)
d_header(‘Content-Type’, ‘your/contenttype’)
t_method = lambda: ‘PUT’
url = (request)
answered Sep 21 ’08 at 20:24
Florian BöschFlorian Bösch26. 3k11 gold badges46 silver badges52 bronze badges
Httplib seems like a cleaner choice.
import lib
connection = TPConnection(‘1. 2. 3. 4:1234’)
body_content = ‘BODY CONTENT GOES HERE’
quest(‘PUT’, ‘/url/path/to/put/to’, body_content)
result = tresponse()
# Now and contains interesting stuff
answered Oct 12 ’10 at 22:13
SpoolesSpooles7856 silver badges16 bronze badges
You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:
pip install requests
More on installing requests.
Then setup the put request:
import requests
import json
url = ”
payload = {‘some’: ‘data’}
# Create your header as required
headers = {“content-type”: “application/json”, “Authorization”: ““}
r = (url, (payload), headers=headers)
See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.
answered Sep 25 ’14 at 18:08
radtekradtek28k9 gold badges129 silver badges99 bronze badges
This was made better in python3 and documented in the stdlib documentation
The quest class gained a method=… parameter in python3.
Some sample usage:
req = quest(”, data=b’DATA! ‘, method=’PUT’)
quest. urlopen(req)
answered Jan 8 ’18 at 3:56
Anthony SottileAnthony Sottile43. 4k10 gold badges91 silver badges135 bronze badges
You should have a look at the lib module. It should let you make whatever sort of HTTP request you want.
answered Sep 21 ’08 at 20:18
John MontgomeryJohn Montgomery8, 2502 gold badges32 silver badges41 bronze badges
I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on lib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.
answered Sep 22 ’08 at 12:46
MikeMike3, 4533 gold badges19 silver badges12 bronze badges
I also recommend lib2 by Joe Gregario. I use this regularly instead of lib in the standard lib.
jbochi27. 2k14 gold badges70 silver badges87 bronze badges
answered Sep 22 ’08 at 17:05
Corey GoldbergCorey Goldberg54. 5k24 gold badges120 silver badges139 bronze badges
Have you taken a look at I’ve used it in the past. You can also just hack up your own request with urllib.
answered Sep 21 ’08 at 20:12
William KellerWilliam Keller5, 0581 gold badge24 silver badges22 bronze badges
You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.
“PyCurl is a Python interface to libcurl. ”
“libcurl is a free and easy-to-use client-side URL transfer library,… supports… HTTP PUT”
“The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl’s C API. ”
answered Sep 21 ’08 at 20:17
wnoisewnoise9, 40533 silver badges46 bronze badges
If you want to stay within the standard library, you can subclass quest:
class RequestWithMethod(quest):
def __init__(self, *args, **kwargs):
self. _method = (‘method’, None)
quest. __init__(self, *args, **kwargs)
def get_method(self):
return self. _method if self. _method else super(RequestWithMethod, self). get_method()
def put_request(url, data):
request = RequestWithMethod(url, method=’PUT’, data=data)
return (request)
answered Jun 27 ’17 at 13:19
Wilfred HughesWilfred Hughes26. 6k14 gold badges123 silver badges180 bronze badges
A more proper way of doing this with requests would be:
response = (url=”, data=payload)
response. raise_for_status()
except questException as e:
This raises an exception if there is an error in the HTTP PUT request.
answered Dec 19 ’19 at 23:17
Adam EricksonAdam Erickson4, 9891 gold badge35 silver badges31 bronze badges
Using urllib3
To do that, you will need to manually encode query parameters in the URL.
>>> import urllib3
>>> = urllib3. PoolManager()
>>> from import urlencode
>>> encoded_args = urlencode({“name”:”Zion”, “salary”:”1123″, “age”:”23″})
>>> url = ” + encoded_args
>>> r = quest(‘PUT’, url)
>>> import json
>>> ((‘utf-8’))
{‘status’: ‘success’, ‘data’: [], ‘message’: ‘Successfully! Record has been updated. ‘}
Using requests
>>> import requests
>>> r = (”, data = {‘key’:’value’})
>>> atus_code
answered Aug 2 ’20 at 18:49
Ransaka RaviharaRansaka Ravihara1, 2391 gold badge9 silver badges22 bronze badges
You can use quest
url = ”
payload=”{\”param1\””: 1

Frequently Asked Questions about request put python

Leave a Reply

Your email address will not be published.