Search code examples
pythonpostrequesturllib2urllib

Am I sending a date object correctly to the request body? Python


I am sending a POST request via python urllib and urllib2 libraries. I am able to send the request, but it is ignoring the dates (values).

In the documentation, it says I need to pass the date object on the request body. Bellow is the code I am using.

url = 'https://api.kenshoo.com/v2/reports/5233/runs/?ks=105'
values = {'dateRange': {'from':'2015-09-22', 'to':'2015-09-22'}}
data = urllib.urlencode(values)

req = urllib2.Request(url, data)

req.add_header('Content-Type', 'application/json; charset=utf-8')
req.add_header('Content-Length', 0)

response = urllib2.urlopen(req)

From the API documentation, this is what I know about the date format.

"The request body must contain a dates range in YYYY-MM-DD format, i.e.

 {"dateRange":{"from":"2014-10-20", "to":"2014-10-22"}}

The complete documentation for the request can be found here http://docs.api.kenshoo.com/#!/Reports/runReport


Solution

  • You should send JSON-formatted document, not urlencoded data:

    url = 'https://api.kenshoo.com/v2/reports/5233/runs/?ks=105'
    values = {'dateRange': {'from':'2015-09-22', 'to':'2015-09-22'}}
    req = urllib2.Request(url)
    req.add_header('Content-Type', 'application/json')
    
    response = urllib2.urlopen(req, json.dumps(values))