Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending POST request to a webservice from python

I'm trying to send a POST request to a restful webservice. I need to pass some json in the request.It works with the curl command below

curl --basic -i --data '<json data string here>' -H Content-type:"text/plain" -X POST http://www.test.com/api

I need some help in making the above request from Python. To send this POST request from python I have the following code so far:

import urllib
url='http://www.test.com/api'
params = urllib.urlencode... #What should be here ?
data = urllib.urlopen(url, params).read()

I have the following three questions:

  1. Is this the correct way to send the resuest ?.
  2. How should i specify the params value ?
  3. Does content-type need to be specified ?

Please Help Thank You

like image 558
Joe Avatar asked Mar 15 '26 17:03

Joe


1 Answers

The documentation for httplib has an example of sending a post request.

>>> import httplib, urllib
>>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
302 Found
>>> data = response.read()
>>> data
'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()
like image 90
Michael Mior Avatar answered Mar 17 '26 06:03

Michael Mior



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!