Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we use POST method in Python using urllib.request?

I have to make use of POST method using urllib.request in Python and have written the following code for POST method.

values = {"abcd":"efgh"}
headers = {"Content-Type": "application/json", "Authorization": "Basic"+str(authKey)}
req = urllib.request.Request(url,values,headers=headers,method='POST')
response = urllib.request.urlopen(req)
print(response.read()) 

I am able to make use of 'GET' and 'DELETE' but not 'POST'.Could anyone help me out in solving this? Thanks

like image 735
Srinivas M.S Avatar asked Jun 30 '26 02:06

Srinivas M.S


1 Answers

If you really have to use urllib.request in POST, you have to:

  1. Encode your data using urllib.parse.urlencode()(if sending a form)
  2. Convert encoded data to bytes
  3. Specify Content-Type header (application/octet-stream for raw binary data, application/x-www-form-urlencoded for forms , multipart/form-data for forms containing files and application/json for JSON)

If you do all of this, your code should be like:

req=urllib.request.Request(url,
     urllib.parse.urlencode(data).encode(),
     headers={"Content-Type":"application/x-www-form-urlencoded"}
)
urlopen=urllib.request.urlopen(req)
response=urlopen.read()

(for forms) or

req=urllib.request.Request(url,
     json.dumps(data).encode(),
     headers={"Content-Type":"application/json"}
)
urlopen=urllib.request.urlopen(req)
response=urlopen.read()

(for JSON). Sending files is a bit more complicated.

From urllib.request's official documentation:

For an HTTP POST request method, data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns an ASCII string in this format. It should be encoded to bytes before being used as the data parameter.

Read more:

  • Python - make a POST request using Python 3 urllib
  • RFC 7578 - Returning Values from Forms: multipart/form-data
like image 65
Adam Jenča Avatar answered Jul 07 '26 04:07

Adam Jenča



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!