Srinivas M.S
Srinivas M.S

Reputation: 55

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

Upvotes: 3

Views: 7185

Answers (3)

Adam Jenča
Adam Jenča

Reputation: 585

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:

Upvotes: 4

Naveen Reddy Marthala
Naveen Reddy Marthala

Reputation: 3123

You can send calls without installing any additional packages.

Call this function with your input data and url. function will return the response.

from urllib import request
import json

def make_request(input_data, url):
    # dict to Json, then convert to string and then to bytes
    input_data = str(json.dumps(input_data)).encode('utf-8')

    # Post Method is invoked if data != None
    req =  request.Request(url, data=input_data)
    return request.urlopen(req).read().decode('utf-8')

Upvotes: 0

bhansa
bhansa

Reputation: 7504

You can use the requests module for this.

import requests
...
url="https://example.com/"
print url
data = {'id':"1", 'value': 1}
r = requests.post(url, data=data)
print(r.text)
print(r.status_code, r.reason)

Upvotes: 0

Related Questions